Question
In the code we have the ElectricPowerSwitch class with a field referencing LightBulb . We see specifics of the light bulb all through the ElectricPowerSwitch
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
Package A Package B Package A Object A Package B Object B References Object A Object B References Interface A Inherits Without Dependency Inversion With Dependency Inversion
Step by Step Solution
There are 3 Steps involved in it
Step: 1
To implement the Dependency Inversion Principle DIP in the provided code well follow the steps outlined Create an interface called Switchable with tur...Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started