Adapter

structural

Converts the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

Intent

The Adapter pattern converts the interface of a class into another interface that clients expect. It lets classes work together that couldn't otherwise because of incompatible interfaces.

Motivation

Sometimes you want to use an existing class, but its interface doesn't match the one you need. The Adapter pattern lets you wrap the existing class with a new interface.

Structure

The pattern involves a Target interface, an Adaptee class with an incompatible interface, and an Adapter that makes the Adaptee's interface compatible with the Target interface.

Participants

  • Target - defines the domain-specific interface that Client uses
  • Adapter - adapts the interface of Adaptee to the Target interface
  • Adaptee - defines an existing interface that needs adapting
  • Client - collaborates with objects conforming to the Target interface

Pros

  • Follows Single Responsibility Principle
  • Follows Open/Closed Principle
  • Increases reusability of existing code
  • Improves flexibility

Cons

  • Increases overall code complexity
  • Sometimes it's simpler to change the service class

Use Cases

Integrating legacy code with new systems
Working with third-party libraries
Converting data formats
Adapting payment gateways
Database driver abstraction

Implementation Tips

Considerations

  • Decide whether to use class or object adapter
  • Consider how much adapting is needed
  • Think about two-way adapters

Tips

  • Use composition over inheritance
  • Keep the adapter focused on interface conversion
  • Consider using multiple adapters for complex conversions
  • Document what interfaces are being adapted

Interactive Code Editor

Related Patterns