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.
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
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Nullbody Notes
Go backend development, learning open-source project source code together, focusing on simplicity and practicality.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
