In the code we have the ElectricPowerSwitch class with a field referencing LightBulb . We see specifics
Question:
In the code we have theElectricPowerSwitchclass with a field referencingLightBulb. We see specifics of the light bulb all through theElectricPowerSwitch. Our switch can now turn on and off the light bulb. But the mistake is apparent. Our high-levelElectricPowerSwitchclass is directly dependent on the low-levelLightBulbclass. But a switch should not be tied to a bulb. It should be able to turn on and off other appliances and devices too, say a fan, an AC, or the entire lightning system of an amusement park. Now, imagine the modifications we will require in theElectricPowerSwitchclass each time we add a new appliance or device. We can conclude that our design is flawed, and we need to revisit it by following the Dependency Inversion Principle.
In a more abstract viewpoint, look at the left example below. Object A is dependent on the lower-level object B, a bad design. So how do we get around this problem? What we do is design an interface that Object A references that Object B uses as in the right-hand side.
We want to use DIP to remove hardcoded dependencies so that the application becomes loosely coupled and extendable.
So how do we do it? First, we want to create one interface for whatever the switch will control. So create one new interface called Switchable with two methods associated with it, turnOn() and turnOff(). We then need to modify our LightBulb class to implement Switchable. Finally, we need to modify ElectricPowerSwitch to use the Switchable interface and remove all references to LightBulb.
Specific Requirements
- Modify the starter code as described in the above paragraph to implement DIP. (Note, the main() class can still reference a light bulb and fan since those will be our test object).
- Add a new class, a fan that does not require changing ElectricPowerSwitch.
- Bonus Points: How would you create one interface that would allow you to create different types of switches (example, RemoteSwitch). Provide a text file describing your solution.
- Reference: Examine the code in https://github.com/ShmilyJxu/Shared/tree/main/DIP-Code/src
Income Tax Fundamentals 2013
ISBN: 9781285586618
31st Edition
Authors: Gerald E. Whittenburg, Martha Altus Buller, Steven L Gill