The final product is oddly satisfying.

 Image for post

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.

Use Cases

The Decorator pattern can be applied to a wide range of situations and scenarios. These include:

  • A Shopping Cart — each item could be wrapped around a central customer order object in order to keep track of the total order price.
  • Data Streaming — as you transfer data you may find out you want various combinations of encryption, compression, or formatting behavior depending on what the client wants.
  • Legacy Code — if you have an object that you can’t change but need to extend its feature capability, you could do so with Decorator pattern.

UML Diagram

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.

Image for post

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

The Decorator Pattern In Go
1.45 GEEK