Senior
Tell me about the Inversion of Control (IoC) pattern.
sobes.tech AI
Answer from AI
The Inversion of Control (IoC) pattern is a design principle where the control of creating and binding object dependencies is delegated to an external container or framework, rather than being implemented within the objects themselves. This reduces component coupling and increases flexibility and testability of the code.
In Java, IoC is often implemented through Dependency Injection, where dependencies are passed to an object via constructor, setters, or interfaces.
Example of dependency injection via constructor:
public class Service {
private final Repository repository;
public Service(Repository repository) {
this.repository = repository;
}
public void doWork() {
repository.save();
}
}
// External code creates dependencies and passes them
Repository repo = new RepositoryImpl();
Service service = new Service(repo);
Thus, the Service class is not responsible for creating the Repository, which makes it easier to replace implementations and test.