Design patterns: Adapter
The Adapter pattern allows incompatible interfaces to work together.
Characteristics of the Adapter pattern
- Compatibility between interfaces: The Adapter Pattern lets you adapt an existing interface to another interface the client expects, enabling incompatible classes to work together.
- 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.
- Reuse of existing code: It lets you reuse existing classes without modifying them, making it easier to integrate new functionality into an application.
- Flexibility: Adapters can easily be created to adapt new classes, keeping the application flexible and making it easier to integrate different components.
- 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.
- 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.
- Incremental development: It supports an incremental development approach, letting you add new features or components without having to restructure the entire system.
- 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();