Structural Design Pattern · Java

Adapter Design Pattern in Java

Connect incompatible interfaces so existing classes can work together.

What is Adapter?

Adapter acts like a translator. It wraps an existing class and exposes the interface that the client expects.

Beginner-friendly Java example

The following example shows the central idea of this pattern in a small, practical scenario.

interface PaymentProcessor {
    void pay(double amount);
}

class LegacyGateway {
    void makePayment(double value) {
        System.out.println("Paid: " + value);
    }
}

class GatewayAdapter implements PaymentProcessor {
    private final LegacyGateway gateway = new LegacyGateway();

    public void pay(double amount) {
        gateway.makePayment(amount);
    }
}

Benefits and trade-offs

Benefits
  • Separates responsibilities clearly.
  • Improves flexibility as the application grows.
  • Encapsulates structural complexity.
Trade-offs
  • Can introduce extra wrapper classes.
  • Choose the pattern only when the complexity is real.

When should you use it?

  • Integrating a legacy library
  • Wrapping a third-party API
  • Converting data between formats
Key takeawayConnect incompatible interfaces so existing classes can work together. Start with the smallest structure that solves the coupling or composition problem.