Adapter pattern using real world example in PHP
I am picking DSLR camera lenses as a real world example:
what is adapter pattern ?
The Adapter Pattern is a design pattern that allows two incompatible interfaces to work together by creating an adapter that maps the methods of one interface to the other
NOW
There are 11 Types Of Camera Lenses (For DSLR) we will be choosing only two to understand the pattern
- Sony Lenses
- Nikon Lenses
interface Lens
{
public function zoomIn();
public function zoomOut();
public function focus();
}
class NikonLens implements Lens
{
public function zoomIn()
{
// code
}
public function zoomOut()
{
// code
}
public function focus()
{
// code
}
}
interface SonyLensInterface
{
public function zoomIn();
public function zoomOut();
public function autofocus();
}
class SonyLens implements SonyLensInterface
{
public function zoomIn()
{
// code
}
public function zoomOut()
{
// code
}
public function autofocus()
{
// code
}
}
class SonyLensAdapter implements Lens
{
protected $sonyLens;
public function __construct(SonyLensInterface $sonyLens)
{
$this->sonyLens = $sonyLens;
}
public function zoomIn()
{
$this->sonyLens->zoomIn();
}
public function zoomOut()
{
$this->sonyLens->zoomOut();
}
public function focus()
{
$this->sonyLens->autofocus();
}
}
Let me explain it !
In the above code say we want to add support for a new type of lens, SonyLens
, that also implements the Lens
interface, but has a different implementation of the methods. To use the SonyLens
with our Camera
class, we can create an adapter class, SonyLensAdapter
, that adapts the SonyLens
to our Lens
interface.
The SonyLensAdapter
class implements the Lens
interface, and wraps a SonyLens
object. The zoomIn()
, zoomOut()
, and focus()
methods of the adapter delegate to the corresponding methods of the wrapped SonyLens
object.
But for focus() SonyLens can
autofocus()
$sonyLens = new SonyLens();
$sonyLensAdapter = new SonyLensAdapter($sonyLens);
$sonyLensAdapter->focus();
Simply that’s it.
Buy me a coffee
Your support allows me to continue improving and providing helpful responses.
If you’re looking for informative and engaging content on backend development,
be sure to follow me today. You won’t want to miss latest articles,
tutorials, and insights on this exciting and dynamic field.
Clap and follow, Thanks.