Golang — Decorator Pattern

Matthias Bruns
3 min readMar 16, 2023

The Decorator Pattern is a design pattern that allows behavior to be added to an individual object, dynamically, without affecting the behavior of other objects from the same class.

The “Gang of Four” patterns book describes the Decorator Pattern as “attaching additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.”

Example

In Golang, the Decorator Pattern can be implemented using interfaces and anonymous functions. Let’s see a code example:

package main

import "fmt"

type Printer interface {
Print() string
}

type SimplePrinter struct {}

func (sp *SimplePrinter) Print() string {
return "Hello, world!"
}

func BoldDecorator(p Printer) Printer {
return PrinterFunc(func() string {
return "<b>" + p.Print() + "</b>"
})
}

type PrinterFunc func() string

func (pf PrinterFunc) Print() string {
return pf()
}

func main() {
simplePrinter := &SimplePrinter{}
boldPrinter := BoldDecorator(simplePrinter)
fmt.Println(simplePrinter.Print()) // Output: Hello, world!
fmt.Println(boldPrinter.Print()) // Output: <b>Hello, world!</b>
}

In the code example above, we declare a Printer interface and a SimplePrinter struct that implements the Print() method.

--

--

Matthias Bruns

Senior Freelancer & Technical Lead Working as a Golang developer since 2020. as a mobile developer since 2013. Focussed on architecture & testability.