All PatternsStructural
Adapter
Allows incompatible interfaces to work together.
Legacy code integrationThird-party librariesAPI wrappers
Understanding Adapter
The Adapter pattern allows two incompatible interfaces to work together by wrapping one interface with another that the client expects. In Go, this is implemented by creating a struct that embeds or holds a reference to the adaptee and implements the target interface, translating method calls between the two. This is one of the most commonly used patterns when integrating third-party libraries or legacy code into a system that expects a different API.
Key Concepts
- •Target interface — the interface the client code expects to work with
- •Adaptee — the existing class or service with an incompatible interface that needs to be adapted
- •Adapter struct — wraps the adaptee and implements the target interface, translating calls between the two
- •No source modification — neither the client nor the adaptee code needs to change — only the adapter is new code
When to Use
✅ Use when
- • Integrating a third-party library with a different API than yours
- • Wrapping legacy code to work with new interfaces
- • You want to create a reusable class that works with unrelated classes
- • You need to use several subclasses but can't adapt their interfaces by subclassing
⚠️ Avoid when
- • You can modify the source of the incompatible class directly
- • The interfaces are only slightly different — a simple wrapper may suffice
- • Too many adapters indicate a architectural mismatch that should be redesigned
Structure
Client
↓ calls Target interface
Adapter (implements Target)
↓ translates and delegates
Adaptee (incompatible interface)
How It Works
Client
expects: Play()
✕
Incompatible!
Adapter
Play() → PlayMP3()
Service
has: PlayMP3()
1
Incompatible Interface
Client expects interface A but service provides interface B.
1 / 4
Basic Implementation
Adapting a legacy MP3 player to a modern interface:
main.go
Loading editor...
Real-World Example: Logger Adapter
Integrating a third-party logging library with your application's interface:
main.go
Loading editor...