Course notes taken for CSCB07/CSC207 at UofT (Software Design).

Decorator pattern.

Classes should be open for extension but closed for modification.

Decorators

public abstract class Beverage {
    String des = "unknown";

    public String getDescription() {
        return this.des;
    }

    public abstract double cost();
}

public abstract class CondimentDecorator extends Beverage {
    public abstract String getDescription();
    public abstract double cost();
}

public class Espresso extends Beverage {
    public Espresso() {
        description = "Espresso";
    }

    public double cost() {
        return 1.99;
    }
}

public class Mocha extends CondimentDecorator {
    Beverage bev;

    public Mocha(Beverage bev) {
        this.bev = bev;
    }

    public String getDescription() {
        return bev.getDescription() + ", Mocha";
    }

    public double cost() {
        return .20 + bev.cost();
    }
}

// Now you can do
Beverage bev = new Mocha(new Espresso());
// You now have mocha! with price of 2.19

Decorator Design Principle

Tradeoffs

Therefore don’t use decotrators everywhere.

Advantages