High-level modules should not depend on low-level modules. Both should depend on abstractions.
Example: Consider a Light class that directly controls a Switch.
// Violation of DIP
public class LightSwitch {
private Light light;
public LightSwitch(Light light) {
this.light = light;
}
public void turnOn() {
light.turnOn();
}
public void turnOff() {
light.turnOff();
}
}
// Following DIP
public interface Switchable {
void turnOn();
void turnOff();
}
public class Light implements Switchable {
public void turnOn() {
System.out.println("Light is On");
}
public void turnOff() {
System.out.println("Light is Off");
}
}
public class Fan implements Switchable {
public void turnOn() {
System.out.println("Fan is On");
}
public void turnOff() {
System.out.println("Fan is Off");
}
}
public class Switch {
private Switchable device;
public Switch(Switchable device) {
this.device = device;
}
public void turnOn() {
device.turnOn();
}
public void turnOff() {
device.turnOff();
}
}
Now, the Switch class depends on the Switchable interface, which could be a Light, Fan, or any other device, making the code flexible and adherent to DIP.
Previous: Interface Segregation Principle (ISP)
Next: SOLID

Leave a Reply