Golang — Adapter Pattern

Matthias Bruns
3 min readMar 14, 2023

The Adapter Pattern, one of the Gang of Four design patterns, is used to enable the interaction between two incompatible interfaces by creating a wrapper object that can translate requests between both interfaces. In Golang, this pattern is quite useful when you have two interfaces, but their functionalities do not match, and you need to make them work together.

Implementation

The Adapter Pattern consists of four components:

  1. Target Interface: the interface that the client is expecting to interact with.
  2. Adapter: the object that implements the Target Interface and wraps the Adaptee.
  3. Adaptee: the interface that needs to be adapted to be used by the client.
  4. Client: the component that uses the Target Interface.

Here is an example implementation of the Adapter Pattern in Golang:

type Target interface {
Request() string
}

type Adaptee interface {
SpecificRequest() string
}

type adapteeImpl struct {}

func (a *adapteeImpl) SpecificRequest() string {
return "Adaptee request"
}

type adapter struct {
adaptee Adaptee
}

func (a *adapter) Request() string {
return "Adapter: " + a.adaptee.SpecificRequest()
}

func main() {
adaptee := &adapteeImpl{}
target := &adapter{
adaptee: adaptee…

--

--

Matthias Bruns

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