Pattern · Core

Decorator

Add behaviour to an object by WRAPPING it in another object of the same type — stack as many layers as you like, at runtime.

Asked atAmazonStarbucksGoogle
step 1 / 9
1/2A subclass per combination
Espresso
EspWithMilk
EspMilkSugar
EspWithSugar
A subclass per combination
1class EspressoWithMilk extends Espresso { ... }
2class EspressoWithMilkAndSugar extends Espresso { ... }
3// every new add-on doubles the subclasses 💥

Modelling each add-on combo as a subclass means a class for every mix — milk, sugar, milk+sugar, …