Decorator — Design Pattern
Hey there! You might have heard a lot about design patterns. In this article, we focus on one of the popular structural design patterns, ”Decorator”.
🤔Problem Statement:
Let’s say, you are given a requirement to count the number of times a given method is called. The brute-force thinking would be to use a global static counter variable and increment it where ever the target method is called.
If you can see the above code, the responsibility to increment the counter lies with the StockService
instead of StockMarket
. The main problem here is, whoever uses the StockMarket
object, needs to take care of incrementing the counter. This leads to boilerplate code. This can be improved by using the decorator pattern.
👀Text book definition for decorator pattern:
In OPPs, the decorator pattern is a structural design pattern, that allows behavior to be added to an individual object dynamically without affecting the behavior of other objects from the same class.
😎Improving our naive solution:
In the previous code snippet, we can extend the StockMarket
object and we can override buy()
the method to extend it to hold the incrementing logic as well.
Here we are applying a generic consuming logic before the original buy implementation is called.
As you can see, instead of creating a direct StockMarket
object, we created the decorated implementation with our custom before logic that increments the buy counter.
With this kind of decorated implementation, we are reducing the boilerplate code and also reducing the human error that could happen if we are to increment the counter manually.
🎈Further Improvements:
Here we are using inheritance to achieve our goal. This might not be an ideal solution if the requirement was to inherit more than one kind of object. In such cases, Aggregation aka Composition could really help.
🎁References:
1. https://refactoring.guru/design-patterns/decorator
2. https://en.wikipedia.org/wiki/Decorator_pattern