Alex Rivera | Logout

Is this a decorator or a strategy pattern, or neither of the two?

Asked 2012-01-24T08:19:12.720
8

I have the following interface.

PowerSwitch.java

public interface PowerSwitch {
    public boolean powerOn();
    public boolean powerOff();
    public boolean isPowerOn();
}

The above interface should consist of the minimum set of methods which any other functionality can be derived from, to make it as easy as possible to add additional PowerSwitch implementations.

I would like to add functionality to the PowerSwitch interface at run-time (what decorators do), by creating a class which holds a composition of a PowerSwitch instance and adds new methods, like the two toggleOnOff() methods below. That way i only need to implement the two toggle methods once and it will apply to all PowerSwitch implementations.

Is this considered as a good/bad practice? If bad, any other recommendations?

It doesn't really comply to the decorator-pattern as it adds extra methods. Is it a strategy pattern, or a composition pattern? Or does it have another pattern name? Is there such thing as an "interface decorator"?

PowerSwitchDecorator.java

public class PowerSwitchDecorator {
    private PowerSwitch ps;

    public PowerSwitchDecorator(PowerSwitch ps) {
        this.ps = ps;
    }

    public void toggleOnOff(int millis) throws InterruptedException{
        powerOn();
        Thread.sleep(millis);
        powerOff();
    }

    public void toggleOnOff(){
    powerOn();
    powerOff();
    }

    public boolean powerOn() {
        return ps.powerOn();
    }

    public boolean powerOff() {
        return ps.powerOff();
    }

    public boolean isPowerOn() {
        return ps.isPowerOn();
    }
}
Edit
Report

1 Answer

0

It would really be a decorator if the decorator also implemented the PowerSwitch interface. I would characterize this as object aggregation.

answered 2012-01-24T08:34:42.600

Your Answer