Portfolio

Blog

My articles

Dependency Inversion Principle (DIP):

  • Description: High-level modules should not depend on low-level modules. Both should depend on abstractions.
  • Before DIP:
class LightBulb {
    public void turnOn() {
        // Turn on the light
    }
}

class Switch {
    private LightBulb bulb;

    public Switch(LightBulb bulb) {
        this.bulb = bulb;
    }

    public void operate() {
        // Turn on/off the light
        bulb.turnOn();
    }
}
  • After DIP:
interface Switchable {
    void turnOn();
}

class LightBulb implements Switchable {
    @Override
    public void turnOn() {
        // Turn on the light
    }
}

class Fan implements Switchable {
    @Override
    public void turnOn() {
        // Turn on the fan
    }
}

class Switch {
    private Switchable device;

    public Switch(Switchable device) {
        this.device = device;
    }

    public void operate() {
        device.turnOn();
    }
}

Web Developer

© Michał Pieróg. All Rights Reserved.

Scroll to Top