Inversion of Control (IOC), Dependency Injection (DI) Oversimplified
IOC and DI patterns details with example in Java.
Join the DZone community and get the full member experience.Join For Free
IOC and DI are very useful patterns that are used in almost every production project. But, for me personally, they are pretty misleading and difficult concepts to understand. Here, I'll example what both of them are and implement a simplified proof of concept.
Inversion of Control
Inversion of control is a pattern responsible for your class initialization. They will be created and set on startup or before each class is initialized. So initialization is not done in constructor but by classes themselves (control is inverted). In a configuration class, you can what implementation each interface will be used.
Two examples do the same thing — the initialize User interface by the MyUser implementation. After, when any class is created ,all user interfaces will be injected by the MyUser class.
This pattern helps initialize fields inside the class not in constructor but somewhere else (e.g. in some configuration class). Often, such fields are highlighted by the @Inject (in Java EE) or @Autowired (in spring) annotation.
On the right side, you can see the same class but with extracted initialization. Dependency Manager is an abstract idea (fake class) that just shows that User is initialized somewhere in the application. Such initialization might be on startup or dynamically when an instance of a class is created.
Instead of Conclusion
As you can see both patterns are pretty straightforward. Together this patterns just initialize interfaces and after set them in classes. Initialization might be more complex — for example you can make each injected instance as new instance instead of singleton. But generally that is it. I hope now those patterns looks much more transparent.
Opinions expressed by DZone contributors are their own.