Facebook Pixel

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.

CommandBehaviorOutput
["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 offThe message returned by the device's turn_on or turn_off method, or "Nothing connected" if nothing is wired
Example
Input
6
connect light
toggle
toggle
connect fan
toggle
connect unknown
Output
Switch connected to light
Light: shining
Light: dark
Switch connected to fan
Fan: spinning
Unknown device: unknown
Explanation
Connecting to "light" stores a `Light` instance behind the `Switchable` field and resets the on/off state to off. The first toggle calls `turn_on` on the `Light`, which returns `"Light: shining"`; the second calls `turn_off`, returning `"Light: dark"`. Connecting to "fan" replaces the device and resets state, so the next toggle calls `Fan.turn_on`, returning `"Fan: spinning"`. Connecting to an unrecognized name returns `"Unknown device: unknown"` without changing any state.

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.

Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro