Adapter
Intent
Lets objects with incompatible interfaces collaborate.
Problem
Your app works with XML, but a great analytics library only accepts JSON.
Solution
Create an adapter that implements the interface your code expects and translates calls to the wrapped object.
Real-world analogy
Think of it like this
A travel plug adapter lets your laptop charger fit a foreign wall socket without changing either.
Structure
Hover or tap a numbered role to highlight it in the diagram.
- 1Client — Client contains the existing business logic.
- 2ClientInterface — Client Interface is the protocol other classes must follow to work with the client.
- 3Service — Service is a useful class (often third-party or legacy) with an incompatible interface.
- 4Adapter — Adapter implements the client interface, wraps the service and translates calls.
Code example
A Go code sample for Adapter is coming soon. Factory Method, Singleton, Decorator, Observer and Strategy already have code in all six languages.
Applicability
Use Adapter when using an existing class whose interface doesn't match.
Use Adapter when reusing subclasses that lack common functionality.
Pros and cons
Pros
- Separates conversion code from business logic
- Open–Closed: new adapters without changing clients
Cons
- Extra indirection
Check yourself
Check yourself
A legacy payment SDK exposes chargeCard(cents) but your code expects pay(amount: Money).
Saved in this browser only. Part of Structural patterns (0/7).