Search code examples
decorator

Why are decorator design patterns always shown as classes and subclasses in examples?


For example, in freecodecamp.org, an example of running a coffee shop is used:

public abstract class Beverage {
private String description;

public Beverage(String description) {
    super();
    this.description = description;
}

public String getDescription() {
    return description;
}

public abstract double cost();
}

They then use subclasses for all the various add-ons such as various roasts and items like sugar/milk:

public abstract class AddOn extends Beverage {
protected Beverage beverage;

public AddOn(String description, Beverage bev) {
    super(description);
    this.beverage = bev;
}

public abstract String getDescription();
}

And they follow up with a couple subclasses of AddOn:

public class Sugar extends AddOn {
public Sugar(Beverage bev) {
    super(“Sugar”, bev);
}

@Override
public String getDescription() {
    return beverage.getDescription() + “ with Mocha”;
}

@Override
public double cost() {
    return beverage.cost() + 50;
}
}

public class Milk extends AddOn {

public Milk(Beverage bev) {
    super(“Milk”, bev);
}

@Override
public String getDescription() {
    return beverage.getDescription() + “ with Milk”;
}

@Override  public double cost() {
    return beverage.cost() + 100;
}
}

What I don't get is, why is everything a subclass, rather than just having everything as a method in Beverage that adds to one big description and adds to a universal cost?


Solution

  • You're right that for these very simple examples one big class might well be better. However, in actual code an individual decorator may well have a lot of code to do its decoration. The Single Responsiblity Principle then applies. We don't want to create a big God class that does lots of things, we want to break things up and modularize somehow. In particular we don't want to always change the same class when we want to change how things work. Decorators allow us to modularize and extend whilst retaining polymorphism and a lot of flexibility about objects we are creating.

    Having said that, whilst decorators are one of the original Gang of Four design patterns, you don't see them much in the real world. You can easily end up with a lot of confusing small classes that don't do a lot. So you have a point, and the pattern is a useful tool in the toolbox but maybe one you won't get out too often.