DEV Community

Iyanu Falaye
Iyanu Falaye

Posted on

Design Patterns: Adapter

It is a structural pattern that allows objects with incompatible interfaces to work together. It helps by converting a class’ interface to a target.

Motivation
Where there’s a need to integrate classes with incompatible interfaces.
To reuse an existing code that does not align with a current system’s interface.

Implementation

Considering there is an existing payment system that supports cards, with the increase in the need for digital wallets, we want to provide support for payment from wallet in our payment system. instead of rewriting the whole system to fit this new mode of payment, we can make use of the adapter pattern to integrate the wallet mode seamlessly.

This is the existing PaymentProcessor interface that handles the card payment. it defines the processPayment method

public interface PaymentProcessor {
    void processPayment();
}
Enter fullscreen mode Exit fullscreen mode

This is the proposed Digital Wallet interface that different wallets can implement e.g. binance, coinbase, etc.

public interface DigitalWallet {
    void makePaymentFromWallet();
}
Enter fullscreen mode Exit fullscreen mode

Using Binance as an example;

public class BinanceWallet implements DigitalWallet{
    @Override
    public void makePaymentFromWallet() {
        System.out.println("making payment from my binance wallet");
    }
}
Enter fullscreen mode Exit fullscreen mode

The Adapter wraps DigitalWallet and provides an implementation that is compatible with PaymentProcessor

public class DigitalWalletAdapter implements PaymentProcessor {
    private DigitalWallet binanceWallet;

    public DigitalWalletAdapter(DigitalWallet binanceWallet) {
        this.binanceWallet = binanceWallet;
    }

    @Override
    public void processPayment() {
        binanceWallet.makePaymentFromWallet();
    }
}
Enter fullscreen mode Exit fullscreen mode

Advantages

  1. Single Responsibility: you can separate the interface and the code that converts from the logic of the program.

  2. Open-Closed principle: you can keep adding adapters without breaking or modifying the existing code.

Disadvantages

  1. Complexity increases

Examples

  1. RecylerView Adapter in Android

Conclusion
When a system needs to evolve, the need for adapter pattern cannot be overstated to make it easier to integrate new functionalities with existing components. It ensures that a system is resilient and adaptable when requirements change.

Top comments (0)