Middle
What problem does the adapter pattern solve?
sobes.tech AI
Answer from AI
Allows objects with incompatible interfaces to work together.
How it works
- An adapter class is created that implements the target interface.
- Inside the adapter, there is an instance of the existing ('adaptee') class.
- The methods of the target interface in the adapter are called, transforming calls to the corresponding methods of the adaptee class.
Example of usage
Working with libraries that have different naming conventions for methods or data structures.
// Target interface we want to use
interface TargetInterface
{
public function request();
}
// Existing class with incompatible interface
class Adaptee
{
public function SpecificRequest()
{
return "Adaptee request";
}
}
// Adapter class
class Adapter implements TargetInterface
{
private $adaptee;
public function __construct(Adaptee $adaptee)
{
$this->adaptee = $adaptee;
}
public function request()
{
// Transforming the call
return $this->adaptee->SpecificRequest();
}
}
// Usage
$adaptee = new Adaptee();
$adapter = new Adapter($adaptee);
echo $adapter->request(); // Outputs: Adaptee request
Advantages
- Reuse of existing code.
- Isolation of client code from changes in adaptee classes.
- Ability to work with multiple incompatible classes through a single interface.