Part 3 of 6 · 3 min read
The pattern
Wrap and forward.
GoF's intent for Decorator is to attach extra responsibilities to an object dynamically, as a flexible alternative to subclassing. It is also called a wrapper.
The trick has two rules. A decorator has the same interface as the thing it wraps, so a client cannot tell the difference. And it holds a reference to the wrapped object and forwards calls to it, adding its own behaviour before or after.
interface Booking { long cost(); String describe(); }
class RoomBooking implements Booking {
private final int hours;
RoomBooking(int h) { hours = h; }
public long cost() { return hours * 500L; }
public String describe() { return "room " + hours + "h"; }
}
abstract class Extra implements Booking {
protected final Booking inner;
Extra(Booking b) { inner = Objects.requireNonNull(b); }
}
class Projector extends Extra {
Projector(Booking b) { super(b); }
public long cost() { return inner.cost() + 150; }
public String describe() { return inner.describe() + " + projector"; }
}
class Catering extends Extra {
private final int people;
Catering(Booking b, int p) { super(b); people = p; }
public long cost() { return inner.cost() + people * 80L; }
public String describe() { return inner.describe() + " + catering for " + people; }
}
class Discount extends Extra {
Discount(Booking b) { super(b); }
public long cost() { return inner.cost() * 90 / 100; }
public String describe() { return inner.describe() + " - 10%"; }
}
A two-hour room costs 1000 (at 500 per hour, made up). Wrapping it in a projector and then catering for 5 gives 1000 + 150 + 400 = 1550, described as "room 2h + projector + catering for 5". Wrapping that in a discount gives 1395, which is 90 percent of 1550.
Booking b = new RoomBooking(2);
b = new Projector(b);
b = new Catering(b, 5);
b = new Discount(b);
The client holds a Booking the whole time. Each wrap returns another Booking. Decorators can be added in any order and any number of times. Two projectors on a one-hour room give 500 + 150 + 150 = 800, described as "room 1h + projector + projector". Order can matter: a discount applied before catering is added gives a different total than a discount applied after. State the order you intend.
GoF names the parts. The Component is the interface (Booking). A ConcreteComponent is the object being decorated (RoomBooking). The Decorator holds a component and matches its interface (Extra). ConcreteDecorators add the behaviour.
Decorator pattern
The Decorator pattern wraps an object in another object with the same interface, which adds behaviour before or after forwarding the call to the wrapped object.
Example: new Projector(new RoomBooking(2)).
Check yourself: 1. What does the full stack from the example cost, and why? 2. Why can a client not tell a decorated booking from a plain one? 3. Why might the order of wrapping matter?