The Decorator Pattern In Go

Israel Miles
Level Up Coding
Published in
4 min readNov 20, 2020

--

The final product is oddly satisfying.

The 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…

--

--

Written by Israel Miles

Software Engineer at Audible. Remote Work Proponent and writer of anything that gets a rant out of me.

Responses (2)