Member-only story

The Decorator pattern: an easy way to add functionality — Hacking with Go

Iede Snoek
3 min readJun 2, 2023

Introduction

The Decorator pattern can be used to dynamically alter or add functionality to existing classes. This pattern is oftern more efficient than subclassing because it relieves us of the need of defining a new object.

So, what does it look like?

To decorate a certain class the following steps must be taken:

  1. Construct a subclass, or in our case an implementation of the interface you want to decorate.
  2. In the Decorator class, make sure you add a reference to the original class.
  3. Also in constructor of the Decorator class, make sure to pass a reference to the original class to the constructor.
  4. Where needed, forward all requests to methods in the original class.
  5. And where needed, change the behaviour of the rest.

This all works because both the Decorator and the original class implement the same interface.

Implementation in Go

The implementation in Go is quite straightforward in this simple example.

Open your commandline or terminal in an empty directory and type:

go mod init…

--

--

Iede Snoek
Iede Snoek

Written by Iede Snoek

A love of music and of programming, that is what makes me tick, over 25 years of experience in IT, and a lifelong love of music is what makes me live.

Responses (1)