Design patterns: Adapter

Mauto 2 min

The Adapter pattern allows incompatible interfaces to work together.

Characteristics of the Adapter pattern

  1. Compatibility between interfaces: The Adapter Pattern lets you adapt an existing interface to another interface the client expects, enabling incompatible classes to work together.
  2. Separation of responsibilities: It promotes separation between the client code and the classes that need to be adapted. The client doesn’t have to change its own code to use the adapted classes.
  3. Reuse of existing code: It lets you reuse existing classes without modifying them, making it easier to integrate new functionality into an application.
  4. Flexibility: Adapters can easily be created to adapt new classes, keeping the application flexible and making it easier to integrate different components.
  5. Uniform interface: It provides a uniform interface that hides the complexity of the underlying classes, simplifying the interaction between the client and the adapted classes.
  6. Ability to adapt different kinds of classes: It can adapt both classes and interfaces, letting you work with various kinds of components, including external objects or third-party libraries.
  7. Incremental development: It supports an incremental development approach, letting you add new features or components without having to restructure the entire system.
  8. Adapting behavior: Besides converting interfaces, adapters can also change or extend the behavior of the adapted objects, allowing for greater customization.

Example in PHP:

class OldPaymentSystem {
    public function pay() {
        return "Payment with the old system.";
    }
}

interface NewPaymentInterface {
    public function processPayment();
}

class PaymentAdapter implements NewPaymentInterface {
    private $oldSystem;

    public function __construct(OldPaymentSystem $oldSystem) {
        $this->oldSystem = $oldSystem;
    }

    public function processPayment() {
        return $this->oldSystem->pay(); // We adapt the old method to the new system.
    }
}

// Usage
$oldPayment = new OldPaymentSystem();
$adapter = new PaymentAdapter($oldPayment);
echo $adapter->processPayment();

BACK TO THE GUIDE

Copiato