However, any code that wants to use the toggleOnOff(int) or toggleOnOff() methods will require an instance of PowerSwitchDecorator , not PowerSwitch . This view hits the decorator's goal, which should be transparent to the client.
If you want all implementations to have these methods, you must include them in the PowerSwitch interface.
Then, as @Ani suggests, you can modify the PowerSwitchDecorator above to extend PowerSwitch so you can do this:
PowerSwitch switch = new PowerSwitchDecorator(new ConcretePowerSwitch()); switch.toggleOnOff();
You now have a variable of type PowerSwitch with the capabilities of PowerSwitchDecorator .
EDIT: Please note that you should only use the installed template if it meets your needs. You can use your approach if it works for you. There is no need to shoe it in a certain order.
What type of facility do you want to go through? You need these methods in your API:
void connect(PowerSwitch powerSwitch, Appliance appliance);
Or methods like this:
void connect(PowerSwitchDecorator powerSwitch, Appliance appliance);
(sorry, these are not very good examples)
If you want the first, then everyone will have to manually βdecorateβ their PowerSwitch to get some convenient methods. It may be convenient for you now, but I think it will be inconvenient for users of your code, and they probably will not worry about it. If you want to use the latter, you must use the PowerSwitchDecorator type in your method signatures, which usually means that you always deal with PowerSwitchDecorator , not raw PowerSwitch es.
Gary buyn
source share