The Adapter pattern
Learn the Adapter pattern that connects incompatible interfaces.
What does the Adapter pattern do?
The Adapter pattern adapts an incompatible class to the interface a client expects. When you have an Adaptee class that does not fit and the client wants a Target interface, you put an Adapter between them to bridge the gap.
The Adapter implements the Target interface and holds an Adaptee instance inside. The request method the client calls is translated into the Adaptee's own method, hiding the mismatch.
The Adapter implementation
The Adapter class implements the Target interface and takes an Adaptee instance in its constructor. The request method the client calls invokes the instance's specificRequest and returns the result.
So the client writes $adapter->request() and gets the specificRequest output of the Adaptee; the translation stays inside the Adapter. Compatibility is reached without touching the Adaptee class.
Exercise Get a compatible response with the Adapter
Write a Target interface (with a request(): string method). Write an Adaptee class whose specificRequest(): string method returns 'compatible response'. Make Adapter implements Target; it takes an Adaptee in its constructor and calls specificRequest inside request. Call the Adapter and print the result.
Show example solution
string; }. Adaptee's specificRequest returns 'compatible response'. Adapter implements Target, takes Adaptee in constructor, request calls specificRequest. Run with new Adapter(new Adaptee()), print ->request().
Example solution:
<?php
interface Target {
public function request(): string;
}
class Adaptee {
public function specificRequest(): string { return 'compatible response'; }
}
class Adapter implements Target {
public function __construct(private Adaptee $adaptee) {}
public function request(): string { return $this->adaptee->specificRequest(); }
}
$a = new Adapter(new Adaptee());
echo $a->request();
Test yourself
-
What does the Adapter pattern do?
- Adds behavior without inheritance
- Guarantees a single instance
- Adapts an incompatible interface to a target
- Creates a new instance
Show answer
Adapts an incompatible interface to a target — Correct. The Adapter adapts an incompatible interface to a target.
-
Match the Adapter concepts
- Target
- the target interface
- Adaptee
- the incompatible class
- Adapter
- the adapter
- request
- the target method
-
The class the Adapter wraps
<?php class Adapter implements Target { public function __construct(private ____ $adaptee) {} public function request(): string { return $this->adaptee->specificRequest(); } }Show answer
<?php class Adapter implements Target { public function __construct(private Adaptee $adaptee) {} public function request(): string { return $this->adaptee->specificRequest(); } }