Home > Enterprise >  Adding function to interface decorator pattern
Adding function to interface decorator pattern

Time:10-04

Hello,

I'm trying to wrap my head around the decorator pattern, and I'm not sure about something :

Is considered a bad practice or a misuse of the pattern to add a function to the interface when I want to add a new functionality ?

For example if I have a Car interface, and I want to make it amphibious with a decoration, is it allowed to add a getAquaticSpeed() function to the interface only for the purpose of adding this functionality ?

Thanks in advance !

Code example :

interface Car{
   public float getSpeed();
}

public class CarFrame implements Car{
    public float getSpeed(){return 0;}
}

public abstract CarDecorator implements Car{
    private Car delegate;

    public CarDecorator(Car delegate){
        this.delegate = delegate
    }

    public float getSpeed(){return delegate.getSpeed();}
}

If i want to add an aquatic speed, colors etc. to my Car, is it allowed to add new function to my main interface ?

Like so :

interface Car{
   public float getSpeed();
   public float getAquaticSpeed();
   public String getColor();
}

CodePudding user response:

You certainly can add to the API of a Decorator, making it a superset of the interface in the object that it wraps. The first sentence in the Decorator chapter of the GoF book is,

Intent
Attach additional responsibilities to an object dynamically.

The UML structure on page 177 of the book shows concrete decorators with addedState as well as AddedBehavior() so attaching a responsibility by adding a function is perfectly acceptable.


With respect to the edit, no you cannot modify the previous interface. That would violate the Single Responsibility Principle, the Open/Closed Principle, and besides that, it would have nothing to do with the Decorator Pattern. If you edit the original interface, a Decorator is useless.

  • Related