The final product is oddly satisfying.
T
he Decorator pattern is an incredibly useful and flexible technique to create forward-thinking code. It allows you to add functionality to an object dynamically at run time instead of compile time. What this means is that you don’t have to manually write new code to extend an object’s feature set, you can simply use the decorator pattern to add behavior as you need it!
It also solves the issue of becoming restricted by an extensive sub-class architecture. Instead of getting lost in inheritance, the Decorator pattern uses lots of smaller classes (in Go’s case structs) in order to wrap functionality around other objects. This way we can have many objects with variations of functionality instead of having to define each individual class.
We will split this article into three parts including the use cases, UML diagram, and implementation in Go for the Decorator pattern.
The Decorator pattern can be applied to a wide range of situations and scenarios. These include:
This pattern entails a pretty compact diagram. Starting from the top, the Component interface requires the method operation()
to be implemented. This is done by both the ConcreteComponent and the Decorator objects themselves. Note the aggregation relationship between Component and Decorator meaning that a Component may have zero to many Decorators, but a Decorator cannot exist without a Component.
Essentially, we have a Component interface with its most basic form implemented by ConcreteComponent. Then the Decorator can be implemented by a ConcreteDecorator and wrapped around the ConcreteComponents.
#programming #tutorial #golang #design