design patterns ·
Adapter
Converts the interface of a class into another interface clients expect, enabling incompatible interfaces to work together.
Theory
Explanation
Intuition first, formal definition second. Skim the bullets if you already know this; read the prose if you don't.
You have a class that does what you need, but its interface is wrong. Instead of rewriting it or the client, write a thin wrapper (adapter) that translates calls.
Adapter implements the Target interface (what the client expects) and wraps an Adaptee instance. When the client calls Target methods, the Adapter translates and delegates to Adaptee methods.
When to use
Integrating legacy code, third-party libraries, converting data formats - any case where interface mismatch prevents reuse.
When not to
When you control both the client and the class - change the interface directly instead of adding an adapter layer.
Key insights
- Object adapter (composition) preferred over class adapter (inheritance) - more flexible
- Adapter is transparent to the client - the client only sees the Target interface
- Multiple adaptees can be wrapped by a single adapter if they share similar operations
- Java's InputStreamReader is a real-world Adapter: adapts InputStream (byte stream) to Reader (char stream)