Decorator Pattern
Learn how to add behaviour to an object by wrapping it in layers, instead of creating a subclass for every combination, using a coffee order and a logging repository.
Think about wrapping a gift. You start with the gift itself. You put it in a box, then you wrap the box in coloured paper, then you tie a ribbon, and finally you add a card. Each layer adds something (protection, colour, decoration), but the thing inside is still the same gift. You can add layers in different orders, skip some, or add a new kind of layer tomorrow without touching the gift.
The Decorator pattern is the code version of gift wrapping. It lets you add behaviour to an object by wrapping it in another object that looks the same from outside. Each wrapper adds its own small piece of behaviour and then passes the work to the object inside.
01The problem: a class for every combination
A cafe sells coffee. A customer can add milk, sugar, whipped cream and caramel, in any combination. The first idea is to use inheritance, a subclass for each kind:
public class Coffee { /* base coffee */ }
public class CoffeeWithMilk extends Coffee { }
public class CoffeeWithSugar extends Coffee { }
public class CoffeeWithMilkAndSugar extends Coffee { }
public class CoffeeWithMilkSugarAndWhip extends Coffee { }
// ... and so onWith only four extras, the number of possible combinations is sixteen. Add a fifth extra and it doubles to thirty-two. Every new extra multiplies the number of classes, and most of the code in them is a copy of the others. This is the same "explosion of classes" we saw with the bird example in Module 2.
Inheritance also has a second weakness: the choice is made when you write the code. You cannot decide at run time that this particular coffee should get one more shot of caramel.
Loading the rest of the lesson…