Decorator Design Pattern
Last updated
Was this helpful?
Last updated
Was this helpful?
structural pattern
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
Client-specified embellishment of a core object by recursively wrapping it.
Wrapping a gift, putting it in a box, and wrapping the box.
You want to add behavior or state to individual objects at run-time. Inheritance is not feasible because it is static and applies to an entire class.
In the above example the Pizza class acts as the Component and BasicPizza is the concrete component which needs to be decorated. The PizzaDecorator acts as a Decorator abstract class which contains a reference to the Pizza class. The ChickenTikkaPizza is the ConcreteDecorator which builds additional functionality to the Pizza class.
Let’s summarize the steps to implement the decorator design pattern:
Create an interface to the BasicPizza(Concrete Component) that we want to decorate.
Create an abstract class PizzaDecorator that contains reference field of Pizza(decorated) interface.
Note: The decorator(PizzaDecorator) must extend same decorated(Pizza) interface.
We will need to now pass the Pizza object that you want to decorate in the constructor of decorator.
Let us create Concrete Decorator(ChickenTikkaPizza) which should provide additional functionalities of additional topping.
The Concrete Decorator(ChickenTikkaPizza) should extend the PizzaDecorator abstract class.
Redirect methods of decorator (bakePizza()) to decorated class’s core implementation.
Override methods(bakePizza()) where you need to change behavior e.g. addition of the Chicken Tikka topping.
Let the client class create the Component type (Pizza) object by creating a Concrete Decorator(ChickenTikkaPizza) with help from Concrete Component(BasicPizza).
To remember in short : New Component = Concrete Component + Concrete Decorator
Pizza pizza = new ChickenTikkaPizza(new BasicPizza());