Decorator Pattern

Problem: The explosion of classes occurs because of N number of combinations for a product, for example, pizza or coffee, which leads to inconsistency in the code like maintainability, scalability, and readability and also requires to addition of more combinations on the requirement. This violates the open-closed principle. If you are required to define a small set of different categories of base functionality then sub-classing makes sense, for example, the List interface is implemented by ArrayList, LinkedList, Stack, Vector. 

Sub-classing is a traditional way of adding functionality using inheritance that is also at compile time. Suppose you ordered a margherita pizza but you want some extra veggies like farmer pizza has but the restaurant denies by saying that they don’t have the option to customize pizza because the software is not allowed to do that, software only has the option to choose from a fixed set of pizzas.

Solution: Decorator pattern is one of the GOF famous design patterns in the structural category which provides a way of increasing the power (functionality) of an object at runtime without modifying existing functionality. Always follow the open-closed principle, open for extension but closed for modification.

In layman terms, a way which gives users freedom to add new choices with the existing base choice. For example, pizza with different base categories also have choices to decorate their pizza with more different toppings.

Leave a Reply

Your email address will not be published. Required fields are marked *