Dependency Inversion: depend on a contract, not a detail
Switch depends on ISwitchable, not on Bulb directly — so the same Switch also works with a Fan.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
Dependency Inversion says high-level code (Switch) should depend on an abstraction (ISwitchable), not on a concrete detail (Bulb). The detail depends on the contract instead — Bulb implements ISwitchable, rather than Switch being hard-wired to know about Bulb.
Code
var lightSwitch = new Switch(new Bulb());
lightSwitch.Press();
interface ISwitchable {
void TurnOn();
}
class Bulb : ISwitchable {
public void TurnOn() => Console.WriteLine("Bulb is on");
}
class Fan : ISwitchable {
public void TurnOn() => Console.WriteLine("Fan is on");
}
class Switch {
private readonly ISwitchable device;
public Switch(ISwitchable device) => this.device = device;
public void Press() => device.TurnOn();
}interface Switchable {
void turnOn();
}
class Bulb implements Switchable {
public void turnOn() { System.out.println("Bulb is on"); }
}
class Fan implements Switchable {
public void turnOn() { System.out.println("Fan is on"); }
}
class Switch {
private final Switchable device;
Switch(Switchable device) { this.device = device; }
void press() { device.turnOn(); }
}
class Main {
public static void main(String[] args) {
Switch lightSwitch = new Switch(new Bulb());
lightSwitch.press();
}
}class Switchable {
public:
virtual void turnOn() = 0;
virtual ~Switchable() = default;
};
class Bulb : public Switchable {
public:
void turnOn() override { cout << "Bulb is on\n"; }
};
class Fan : public Switchable {
public:
void turnOn() override { cout << "Fan is on\n"; }
};
class Switch {
Switchable& device;
public:
Switch(Switchable& device) : device(device) {}
void press() { device.turnOn(); }
};
int main() {
Bulb bulb;
Switch lightSwitch(bulb);
lightSwitch.press();
}from typing import Protocol
class Switchable(Protocol):
def turn_on(self) -> None: ...
class Bulb:
def turn_on(self) -> None: print("Bulb is on")
class Fan:
def turn_on(self) -> None: print("Fan is on")
class Switch:
def __init__(self, device: Switchable):
self.device = device
def press(self) -> None:
self.device.turn_on()
light_switch = Switch(Bulb())
light_switch.press()Tips
- Without the interface, Switch would need a field of type Bulb, and wiring a Fan to the same switch would mean editing Switch itself.
- Dependency Inversion is the design idea. Constructor injection — passing the device in through the constructor — is just the technique used to supply it.
In the .NET library
Because Switch only knows about ISwitchable, new Switch(new Fan()) works with no change to Switch at all. The switch and the device can be developed and tested independently.