Inversion of control IOC is a generic term meaning,transfer of control from main applilcation to a container/framework , for instance rather than having the application call the methods in a framework, the framework calls implementations provided by the application.
Example of IOC
- Dependency injection :Dependency injection is basically providing the objects that an object needs (its dependencies) by framework/container, instead of having it construct them itself. It's a very useful technique for testing, since it allows dependencies to be mocked or stubbed out. In other words when using dependency injection, objects are given their dependencies at run time rather than compile time .Hence loose coupling between object and depedencies is possible . Read more about depenency injection https://clarifyforme.com/posts/5684299340709888/what-is-dependency-injection.
- The service locator pattern : The service locator pattern includes "service locator" object that contains information about all the services that an application provides.The ServiceLocator is responsible for returning instances of services when they are requested for by the service consumers or the service clients.Here is simplified example code for service locator pattern.
interface IService { public String getServiceName(); public void executeService(); } class ServiceOne implements Service { public void execute() { System.out.println(" Running ServiceOne"); } public String getServiceName() { return "ServiceOne"; } } class ServiceTwo implements Service { public void execute() { System.out.println(" Running ServiceTow"); } public String getServiceName() { return "ServiceTwo"; } } /*the service locator class will be used by clients to get instance of service*/ class ServiceLocator { public static IService getService(String name) { if(name.equals("serv1")){ return new Service1(); }else if(name.equals("serv2")){ return new Service2(); } } }