Senior
What is inversion of control (IoC), how is this principle implemented, and what is it used for?
sobes.tech AI
Answer from AI
Inversion of Control (IoC) is a design principle where the control of creating and binding objects is delegated to an external container or framework, rather than being implemented within the components themselves. This reduces component coupling and increases system flexibility.
In Java, IoC is often implemented through Dependency Injection (DI). Instead of a class creating its dependencies itself, they are provided from outside, for example, via constructors, setters, or interfaces.
Uses of IoC:
- Simplifies testing, as dependencies can be replaced with mocks.
- Enhances modularity and reusability of code.
- Eases management of object lifecycle.
Example of dependency injection via constructor:
public class Service {
private final Repository repository;
public Service(Repository repository) {
this.repository = repository;
}
public void perform() {
repository.save();
}
}
// External container creates and injects dependencies
Repository repo = new RepositoryImpl();
Service service = new Service(repo);