Cheatsheet
Decorator
Intent
Add responsibilities to an object by wrapping it in others with the same interface, instead of creating a subclass for every combination.
Structure (UML)
classDiagram
direction LR
class Membership {
<<Component>>
+description() String
+monthlyFee() Money
}
class BasicMembership {
<<ConcreteComponent>>
+description() String
+monthlyFee() Money
}
class MembershipDecorator {
<<Decorator>>
#Membership inner
}
class PhysioAddOn {
<<ConcreteDecorator>>
+description() String
+monthlyFee() Money
}
class NutritionAddOn {
<<ConcreteDecorator>>
}
class OpenGymAddOn {
<<ConcreteDecorator>>
}
class StudentDiscount {
<<ConcreteDecorator>>
}
Membership <|.. BasicMembership
Membership <|.. MembershipDecorator
MembershipDecorator o-- Membership : inner
MembershipDecorator <|-- PhysioAddOn
MembershipDecorator <|-- NutritionAddOn
MembershipDecorator <|-- OpenGymAddOn
MembershipDecorator <|-- StudentDiscountParticipants
- Component (Membership), the interface shared by plans and extras
- ConcreteComponent (BasicMembership), the base plan everybody wraps
- Decorator (MembershipDecorator), which keeps the wrapped object and delegates to it
- ConcreteDecorator (PhysioAddOn, NutritionAddOn, OpenGymAddOn, StudentDiscount), which add their part
PhysioAddOn.java
public class PhysioAddOn extends MembershipDecorator {
public PhysioAddOn(Membership inner) {
super(inner);
}
@Override
public String description() {
return inner.description() + " + Physio"; // what's inside, plus my bit
}
@Override
public Money monthlyFee() {
return inner.monthlyFee().plus(Money.eur("25.00"));
}
}Pros
- Combinations are assembled at runtime, with no class per combination
- Each extra lives in a small class and is tested on its own
- The client still sees a Membership, with no layers or with all four
Cons
- If a decorator isn't purely additive, the order of the layers changes the result
- Many small layers are harder to debug than one class
- Anyone asking for the concrete type (instanceof) sees the outer decorator, not the base plan