Inversion of Control

What is Inversion of Control (IoC)?

Inversion of Control is a design principle in which the control of object creation and dependency management is transferred from the program to a framework or container. Instead of the class controlling its dependencies, an external entity provides them.

This is commonly used to achieve loose coupling.

There are two main forms of IoC:

  1. Dependency Injection (DI) – dependencies are injected into a class.
  2. Service Locator pattern – class looks up dependencies from a registry or container.

We’ll focus on Dependency Injection, which is the most common form.


Example in Java (Without IoC)

class Engine {
    void start() {
        System.out.println("Engine started");
    }
}

class Car {
    private Engine engine;

    public Car() {
        engine = new Engine(); // Car controls the creation of Engine
    }

    void startCar() {
        engine.start();
        System.out.println("Car started");
    }
}

public class Main {
    public static void main(String[] args) {
        Car car = new Car();
        car.startCar();
    }
}

Problem: Car is tightly coupled with Engine. If you want to use a different Engine, you need to modify Car.


Example in Java (With IoC / Dependency Injection)

class Engine {
    void start() {
        System.out.println("Engine started");
    }
}

class Car {
    private Engine engine;

    // Engine is injected through constructor
    public Car(Engine engine) {
        this.engine = engine;
    }

    void startCar() {
        engine.start();
        System.out.println("Car started");
    }
}

public class Main {
    public static void main(String[] args) {
        Engine engine = new Engine(); // Main creates the dependency
        Car car = new Car(engine);    // Inject it into Car
        car.startCar();
    }
}

✅ Advantages:

  • Car is no longer responsible for creating Engine.
  • We can inject different types of engines (e.g., ElectricEngine) without modifying Car.
  • Easier to test (we can inject mock engines).

Leave a Reply