Golang Adapter Pattern

In this post, we will learn how to implement the Adapter Design Pattern in Golang with an example.

Adapter Design Pattern convert the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

In plain words, the Adapter pattern lets you wrap an otherwise incompatible object in an adapter to make it compatible with another class. 

Class Diagram


1. Target
  • defines the domain-specific interface that the Client uses.
2. Client
  • collaborates with objects conforming to the Target interface.
3. Adaptee
  • defines an existing interface that needs adapting. 
4. Adapter
  • adapts the interface of Adaptee to the Target interface.

Adapter Design Pattern Implementation

Let's say you have an IProcessor interface with a process() method, the Adapter class implements the process() method and has an Adaptee instance as an attribute. 

The Adaptee class has a convert() method and an adapterType instance variable. The developer while using the API client calls the process() interface method to invoke convert on Adaptee

Let's write the complete code for Adapter Pattern implementation in Golang.

Let's create a file named "adapter.go" and add the following source code to it:


package main

// importing fmt package
import (
	"fmt"
)

//IProces interface
type IProcess interface {
	process()
}

//Adapter struct
type Adapter struct {
	adaptee Adaptee
}

//Adapter class method process
func (adapter Adapter) process() {
	fmt.Println("Adapter process")
	adapter.adaptee.convert()
}

//Adaptee Struct
type Adaptee struct {
	adapterType int
}

// Adaptee class method convert
func (adaptee Adaptee) convert() {
	fmt.Println("Adaptee convert method")
}

// main method
func main() {

	var processor IProcess = Adapter{}

	processor.process()

}

Output:

G:\GoLang\examples>go run adapter.go
Adapter process
Adaptee convert method

Comments