Adapter Pattern

March 23, 2026

Adapter pattern

Adapter = convert interface so old code can work with new code

Old code: a single class (A)

Convert: a new Interface and put A into a new class (implement interface)

Example

// Existing (incompatible) class
class OldPrinter {
    void printOld(String text) {
        System.out.println("Old: " + text);
    }
}

// Target interface (what client expects)
interface Printer {
    void print(String text);
}

// Adapter
class PrinterAdapter implements Printer {
    private OldPrinter oldPrinter;

    public PrinterAdapter(OldPrinter oldPrinter) {
        this.oldPrinter = oldPrinter;
    }

    public void print(String text) {
        oldPrinter.printOld(text); // convert call
    }
}

How to use Adapter pattern in Spring

Step 1: External service (incompatible)

class ThirdPartyPayment {
    public void makePayment(double amount) {
        System.out.println("Paid via external API");
    }
}

Step 2: Your standard interface

public interface PaymentService {
    void pay(double amount);
}

Step 3: Adapter (Spring Bean)

import org.springframework.stereotype.Component;

@Component
public class PaymentAdapter implements PaymentService {

    private final ThirdPartyPayment thirdParty;

    public PaymentAdapter() {
        this.thirdParty = new ThirdPartyPayment();
    }

    @Override
    public void pay(double amount) {
        thirdParty.makePayment(amount); // adapt here
    }
}

Step 4: Use it anywhere

@Service
public class OrderService {

    private final PaymentService paymentService;

    public OrderService(PaymentService paymentService) {
        this.paymentService = paymentService;
    }

    public void checkout() {
        paymentService.pay(100);
    }
}

Overall

  • Adapter: use a old class into another new class that implement Interface
  • Factory Method: use a Interface into Abstract class