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();
    }
}
1
  • 5
    Why doesn't PowerSwitchDecorator implement the PowerSwitch interface? It certainly could...
    – Ani
    Jan 24, 2012 at 8:22

7 Answers 7

7

As it is, any code that wants to use the toggleOnOff(int) or toggleOnOff() methods is going to need an instance of PowerSwitchDecorator, not PowerSwitch. This kind of defeats the purpose of a decorator which should be transparent to the client.

If you want all implementations to have these methods, you should include them in the PowerSwitch interface.

Then, as @Ani suggests, you could modify the above PowerSwitchDecorator to extend PowerSwitch so you can do this:

PowerSwitch switch = new PowerSwitchDecorator(new ConcretePowerSwitch());
switch.toggleOnOff();

Now you have a variable of type PowerSwitch with the PowerSwitchDecorator's capabilities.

EDIT: Note that you should only use an established pattern if it meets your needs. You can use the approach you have shown if it works for you. No need to shoe-horn it into a specific pattern.

What type of object do you want to pass around though? Do you want methods like this in your API:

void connect(PowerSwitch powerSwitch, Appliance appliance);

Or methods like this:

void connect(PowerSwitchDecorator powerSwitch, Appliance appliance);

(sorry, they're not very good examples)

If you want the former, then everyone is going to have to manually 'decorate' their PowerSwitch just to get a couple of convenience methods. It may be convenient for you now but I think that it will be inconvenient for users of your code and they will probably not bother with it. If you want the latter, you have to use the type PowerSwitchDecorator in your method signatures, which tends to mean that you always deal with PowerSwitchDecorators and not raw PowerSwitches.

6
  • 1
    But wouldn't this mean I need to implement dummy methods (toggleOnOff) in all powerswitch implementations? and additionally, if I want to add a new method later on (let's say toggleOffOn) in the Decorator, then I need to add it in the PowerSwitch interface and update all current PowerSwitch implementations (as they won't compile anymore)? Might also be the case I don't have access to all powerSwitch implementations (might be part of a service provider interface).
    – etxalpo
    Jan 24, 2012 at 8:44
  • 1
    As etxalpo, I disagree. By just making the decorator implement the decorated interface, it's still useful because all the clients of a PowerSwitch can use a PowerSwitchDecorator. Just as all the clients of an Reader can use a BufferedReader transparently. This doesn't prevent the BufferedReader to add its own methods (readLine() for example) and for this pattern to be extremely useful.
    – JB Nizet
    Jan 24, 2012 at 8:49
  • Yes that's right. You would probably want an abstract class with basic toggle methods that all of your implementations inherit from. Then if you want a specific way of toggling you could decorate it. I edited my answer, hopefully it helps ;) Jan 24, 2012 at 9:04
  • @JB Fair enough. That's exactly right. I guess it depends on the intended usage. Jan 24, 2012 at 9:07
  • @JB I may have based my answer too much on his mentions of wanting it in all implementations and that this was just for convenience. Jan 24, 2012 at 9:12
3

That's a good practice in the case you need to enhance your PowerSwitch instance at runtime. I recommend you to implement The PowerSwitch interface in the decorator. The other name of decorator pattern is proxy pattern.

You can define the extended methods in another interface which extends your PowerSwitch interface. That will avoid having a dependency on the decorator when these extended methods are needed to be called.

Extending a class is a good practice when you need to enhance or redefine a behavior at compilation.

1
  • Thanks! I will have the decorator implement the PowerSwitch interface
    – etxalpo
    Jan 24, 2012 at 8:31
0

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

0

It is neither of the patterns.

A decorator has the intention to wrap an object and extend the already existing functionality making the interface transparent for the client. An BufferedInputstream is an example. Note that the Decorator should implement the same interface as the Type you are wrapping.

//Let Type be the interface that both the Decorator and DecoratedClass implements
Type yourInstance = new Decorator(new DecoratedClass());

Note the difference from the Proxy-pattern, where the main intention is to control access to an object, not necessarily by wrapping another object. In this case you would also let the proxy implement the same interface.

2
  • Do you mean "Note that..." and "Note the difference..." when you say "Not that..." and "Not the difference..."?
    – JB Nizet
    Jan 24, 2012 at 8:44
  • Yes, sorry for the typo. Thank you! Jan 24, 2012 at 8:46
0

Several patterns often look similar, the difference lies in the intent of their usage. Here's a more general thread on this topic: When and How Strategy pattern can be applied instead of decorator pattern?

With your code, there is no real difference yet. It looks like a strategy, as the PowerSwitchDecorator is merely delegating the work (i.e. the algorithm) to a PowerSwitch. If that is your intention and there are alternate PowerSwitches toggling in different ways, the strategy pattern is your choice.

If instead you have a set of PowerSwitches, each enhancing the toggling in a slight way (decorating the toggling) and these PowerSwitches can be nested, then you are implementing a decorater. As has been said before, in this case you also need the decorators to be part of the type hierarchy.

0

I would say it is none of the patterns.

Decorator pattern

The decorator pattern is used to extend the behavior of an existing implementation. Take a graphic window as an example, you might want to have a window that has scroll bars. Then you can have a class like

public class ScrollBarsWindow : Window
{
     private Window windowToDecorate;
     public ScrollBarsWindow(Window windowToDecorate)
     {
         this.windowToDecorate = windowToDecorate;
     }

     public void Draw()
     {
         windowToDecorate.Draw();
         DrawScrollBars();
     }

     public void DrawScrollBars()
     { Draw the scroll bars }
 }

The strategy pattern

The strategy pattern is used to do different things depending on the chosen strategy. Let's say you are making some coffee. The you could have something like:

public interface IMakeCoffeeStrategy
{
    public Coffee MakeCoffee();
}

public class CappuccinoStrategy : IMakeCoffeeStrategy
{
    public Coffee MakeCoffee { make your cappuccion }
}

public class LatteStrategy : IMakeCoffeeStrategy
{
    public Coffee MakeCoffee { make your latte }
}

public class Context
{
    private IMakeCoffeeStrategy strategy;
    public Context(IMakeCoffeeStrategy strategy)
    {
        this.strategy = strategy;
    }

    public Coffee MakeSomeCoffee()
    {
        return strategy.MakeCoffee();
    }
}

and use it like

public class MyCoffeeMachine
{
    public Coffee MakeCoffee(CoffeeType coffeeType)
    {
        if(coffeeType == CoffeeType.Latte)
            return new Context(new LatteStrategy()).MakeSomeCoffee();
        else if(coffeeType == CoffeeType.Cappuccino)
            return new Context(new CappuccinoStrategy()).MakeSomeCoffee();

       ...
    }
}

Read the following links for more information:

0

Your PowerSwitchDecorator class is not decorator. Your implementation is close to Strategy_pattern even though the commands resemble Command_pattern

In Decorator pattern, Decorator actually implements the interface ( i.e. Component) and your class is not doing the same.

Have a look at class diagram

enter image description here

In above diagram, Component is an interface. Decorator implements Component interface and contains the interface with Composition. Look at member variable - component.

Refer to these questions for better understanding:

Decorator Pattern for IO

Real World Example of the Strategy Pattern

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.