Exercise: Dependency Inversion
This exercise puts the Dependency Inversion Principle into code. You will build a switch that controls devices through an abstraction rather than depending on any concrete device class.
Scenario
A Switch controls devices — initially a Light and a Fan. The switch holds its connected
device as a Switchable reference, never as Light or Fan directly. Both the high-level
Switch and the low-level device classes depend on the Switchable abstraction. The switch
is driven by a sequence of commands.
Commands
The program reads a list of commands, one per line, and prints one line of output per command.
| Command | Behavior | Output |
|---|---|---|
["connect", device] | Wire the switch to "light" or "fan"; resets state to off | "Switch connected to <device>", or "Unknown device: <device>" |
["toggle"] | Flip the connected device; alternates on/off starting from off | The message returned by the device's turn_on or turn_off method, or "Nothing connected" if nothing is wired |
6 connect light toggle toggle connect fan toggle connect unknown
Switch connected to light Light: shining Light: dark Switch connected to fan Fan: spinning Unknown device: unknown
Your task
Create the Light and Fan classes — each implements Switchable with its own turn_on() and turn_off() messages — then implement connect and toggle on Switch so it delegates to the Switchable abstraction. The Switch.connect method below already instantiates Light() and Fan() by name, so the code tells you exactly what to build.