Monday, April 11, 2022

SKP's GoF Design Patterns a Day - 10 - Decorator

[GitHub Repository for Code Samples]

Was going through the book ‘Head First Design Patterns’, came up with my own examples to understand them further. Try downloading the code and see if it helps you in comprehending these in a better way.

Decorator Pattern [Sample Code]
Decorator Pattern provides an elegant way to use composition for enhancing functionality, where the result expected has direct dependency on the composed and composing class. A chain relation (via composition) or decoration can be finally used to achieve the desired output at runtime. In real-time, when the functionality of one particular product is expected to be built form a base product and various other related sub-products or fixtures, we can rely on the Decorator.
Fig. 2 : Decorator (Structural) Design Pattern - Class and Sequence Diagram 
[Source : Wikipedia]

The attached example is that of a Pizza application. Here, the pizzas in the shop are made with various combinations of bases and topping combinations. This is a classical example for usage of the decorator pattern. Pizza is the abstract base class for each of the pizza bases to implement and ToppingDecorator is another abstract class that inherits from Pizza for each of the toppings to implement. Hawaiian, Italian and Mexican are the concrete implementation of Pizza whereas Mushroom, Onion and Chicken are the concrete implementations of ToppingDecorator. Each of these toppings encapsulates a Pizza instance. This instance, at runtime, will hold another topping or the pizza base instance. Finally, it is when the cost has to be calculated on the entire pizza that the real value of decorator pattern is seen and just one call suffices to calculate the entire bill value.

PizzaWorld is the main class. Try adding more decorators and pizza base classes to see if you can get a real taste of the Decorator!

No comments: