design patterns · structural

Adapter

Converts the interface of a class into another interface clients expect, enabling incompatible interfaces to work together.

easystructural0.5h
Ask GPTConfidence

Pattern

Overview

Intent

Convert the interface of a class into another interface clients expect. Adapter lets classes work together that could not otherwise because of incompatible interfaces.

Real-World Analogy

A power plug adapter - your laptop has a US plug, European socket. The adapter sits between them, translating without modifying either.

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.

Participants

TargetAdapterAdapteeClient

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)