Design Pattern Download: The Decorator Pattern
The Decorator pattern is a Structural Pattern used in software engineering when you want to add functionality to an existing object without the need to create a subclass.
Example
We want to create a program to put toppings on an ordinary pizza and then update the topping list and price, we have a lot of toppings so we cannot create subclasses for every single variation of topping combo, and we have some complex work that needs to be done in adding a topping so we do not want to manually access the Pizza’s functions from the main function.
When to use the Decorator?
- When we want to extend the functionality or properties of an existing object.
- When extending a subclass is impractical or undesirable.
What is the Decorator Pattern composed of?
- Overarching interface (the base interface which our decorator and object will implement)
- The Base (The Base class in our case a boring old cheese pizza)
- The Base Decorator ( a class which takes in the Base object on construction and delegates all functions to that base class)
- The Decorators ( classes which will invoke the super Base Decorator but then will provide additional functionality after the fact)
Implementation
The Interface
The Base
The Base Decorator
Notice how in each of these functions, we simply pass to the given pizza.
The Decorators
In both of these Decorators we invoke the super class which will do the behavior of the cheese pizza in the case of functions (in this case it just declares an instance variable). THEN we add the extra stuff, adding to the cost and putting another topping on.
In the end, you can run an application like the one below
which will spit out
5
[]
7
[Pepperoni]
17
[Pepperoni, Truffle]