Adapter

Category

Structural pattern

Problem

Allow two incompatible interfaces to work together. When a class has an interface that clients don’t expect, or when you need to reuse an existing class whose interface doesn’t match your needs.

Solution

  • Create an adapter class that implements the expected interface
  • The adapter wraps the existing class and translates calls to its interface into calls on the adapted class
  • Clients interact with the adapter as if it were the expected interface

Structure

  • Target: The interface clients expect
  • Adapter: Implements Target and wraps Adaptee
  • Adaptee: The existing interface that needs adapting
  • Client: Code that expects the Target interface

Key Benefits

  • Reusability — Reuse existing classes that don’t match the expected interface
  • Loose coupling — Client and Adaptee are decoupled through the Adapter
  • Open/Closed Principle — New adapters can be added without modifying existing code

Trade-offs

  • Adds an extra layer of indirection that can obscure the actual implementation
  • May require multiple adapters for different target interfaces

When to Use

  • You want to use an existing class, but its interface is not compatible with your needs
  • You need to create a reusable class that cooperates with unrelated or unforeseen classes
  • Multiple existing classes have similar interfaces but differ in subtle ways

Examples