Fundamentals 3 min read

Understanding the Adapter Pattern in Go

The article explains the Adapter pattern by defining its purpose, illustrating the concept with mobile charging ports, and providing a complete Go code example that shows how to wrap incompatible interfaces so they can work together through adapters.

Nullbody Notes
Nullbody Notes
Nullbody Notes
Understanding the Adapter Pattern in Go

Adapter Pattern (Adapter)

Definition

Convert the interface of a class into another interface that clients expect, allowing classes that are otherwise incompatible to work together.

Understanding

Different mobile devices use various charging connectors, yet all power sources connect via a USB interface. This illustrates the need for an adapter.

Code Example

package main

import (
    "fmt"
)

type USB interface {
    Work()
}

// External function that expects a USB interface
func Charge(usb USB) {
    usb.Work()
}

// TypeC does not implement USB, cannot be charged directly
type TypeC struct{}

func (t TypeC) IPhone() {
    fmt.Println("Charge IPhone")
}

// AdapterTypeC embeds TypeC and implements USB
type AdapterTypeC struct {
    TypeC // composition
}

func (t AdapterTypeC) Work() {
    t.IPhone()
}

// Alternative adapter using a member variable
type AdapterTypeC1 struct {
    tc TypeC
}

func (t AdapterTypeC1) Work() {
    t.tc.IPhone()
}

// Micro implements USB and can charge Android devices
type Micro struct{}

func (t Micro) Work() {
    fmt.Println("Charge Android")
}

func main() {
    Charge(Micro{})
    Charge(AdapterTypeC{})
    Charge(AdapterTypeC1{tc: TypeC{}})
    // Charge(TypeC{}) // only structs that implement USB can be charged
}

Charge can only supply power to types that implement the USB interface; structs that do not must be wrapped with an adapter that provides the required interface.

Source code repository: https://github.com/gofish2020/gopattern/tree/main/structure/adapter

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Design PatternsGoCode ExampleAdapter PatternInterface
Nullbody Notes
Written by

Nullbody Notes

Go backend development, learning open-source project source code together, focusing on simplicity and practicality.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.