Skip to content
Structural

Adapter

Convert the interface of a class into another interface clients expect, enabling classes to work together that otherwise could not due to incompatible interfaces.

Intent

Allow two incompatible interfaces to collaborate by wrapping one object with an adapter that translates calls from the expected interface into the actual interface of the wrapped object.

Problem

You need to integrate a third-party library, legacy module, or external service whose interface does not match the one your application expects. Rewriting the existing code is impractical or impossible because you do not own it, or because many other consumers already depend on it.

Solution

Introduce an adapter class that implements the target interface your code expects and internally delegates to the incompatible object, translating method signatures, data formats, or protocols as needed. The rest of your application interacts only with the target interface, remaining oblivious to the adaptation happening underneath.

Participants

  • Target -- the interface the client expects
  • Adaptee -- the existing class or service with an incompatible interface
  • Adapter -- translates calls from the Target interface to the Adaptee
  • Client -- collaborates with objects through the Target interface

Advantages

  • Single Responsibility -- translation logic lives in one place, separate from business logic
  • Open/Closed -- new adapters can be introduced without modifying existing client code or the adaptee
  • Reuse of existing, tested code that otherwise would not fit the required interface
  • Decouples clients from third-party or legacy implementation details

Disadvantages

  • Adds an extra layer of indirection, which can obscure debugging and stack traces
  • If the adaptee's interface is very different, the adapter can become complex and hard to maintain
  • Proliferation of adapter classes when many incompatible interfaces need bridging

Real-World Analogy

A power plug adapter lets you use a European appliance in an American outlet. The appliance (adaptee) has a round-prong plug, your wall outlet (target) has flat slots, and the physical adapter translates between the two shapes without modifying either the appliance or the outlet.

Use Cases

  • Wrapping a legacy XML-based API to expose a modern JSON interface
  • Integrating a third-party payment gateway whose SDK does not match your internal PaymentProcessor interface
  • Connecting an old database driver to a new ORM abstraction layer
  • Translating between different logging frameworks so application code uses one consistent API
  • Bridging platform-specific APIs behind a unified cross-platform interface

Code Examples

A class adapter that wraps a legacy XML payment gateway behind a modern JSON-based PaymentProcessor interface, translating data formats transparently.