Middle+
What is the difference between the 'adapter' and 'decorator' patterns?
sobes.tech AI
Answer from AI
Adapter transforms the interface of one class into the interface expected by another class, providing compatibility between classes with incompatible interfaces. It changes the signature of existing methods to match the new interface.
Decorator dynamically adds new responsibilities to an object by wrapping it in a decorator. It does not change the interface of the decorated object but only extends its functionality.
| Criterion | Adapter | Decorator |
|---|---|---|
| Purpose | Interface compatibility | Functionality extension |
| Interface change | Yes, transforms one into another | No, preserves the existing |
| Structure | Wraps the adaptable object | Wraps the decorated object |
| Behavior | Changes calls to the adaptable object | Adds new actions or modifies existing ones |
| Example | Converting XML to JSON | Adding logging to an existing class |
<?php
// Adapter example
interface TargetInterface {
public function request();
}
class Adaptee {
public function specificRequest() {
echo "Specific request of Adaptee" . PHP_EOL;
}
}
class Adapter implements TargetInterface {
private $adaptee;
public function __construct(Adaptee $adaptee) {
$this->adaptee = $adaptee;
}
public function request() {
// Transforming the call
$this->adaptee->specificRequest();
}
}
// Decorator example
interface Component {
public function operation();
}
class ConcreteComponent implements Component {
public function operation() {
echo "Concrete component operation" . PHP_EOL;
}
}
class Decorator implements Component {
protected $component;
public function __construct(Component $component) {
$this->component = $component;
}
public function operation() {
$this->component->operation();
}
}
class ConcreteDecoratorA extends Decorator {
public function operation() {
parent::operation();
$this->addedBehaviorA();
}
private function addedBehaviorA() {
echo "Added behavior A" . PHP_EOL;
}
}