Member-only story
The Decorator pattern: an easy way to add functionality — Hacking with Go
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:
- Construct a subclass, or in our case an implementation of the interface you want to decorate.
- In the Decorator class, make sure you add a reference to the original class.
- Also in constructor of the Decorator class, make sure to pass a reference to the original class to the constructor.
- Where needed, forward all requests to methods in the original class.
- 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…