Adapter pattern – Design Pattern

adapter pattern

Lets Have a Look at adapter pattern definition, that states clearly about its use case.

The Adapter pattern converts the interface of a class into another Interface that client expect. Adapter lets classes work together that could not just because of incompatible interfaces

lets have a look at below code that will give you a better idea.

<?php

class ENumeration Implements Iterator {

    protected $enumobj; // will hold the Adaptee class instance

    public function ENumertion(Enum enumObject)
    {
        $this->enumobj = enumObject;
    }

    public function hasNext()
    {
        return $this->enumobj->hasNextElement();

        //NOTE here hasNextElement method is lying in Enum class, call to hasNext() is being tranfered to Enum class objects hasNextElement() method.
    }

    public function next()
    {
        return $this->enumobj->getNextElement();
        
        //NOTE here getNextElement method is lying in Enum class, call to next() is being tranfered to Enum class object's getNextElement() method.
    }

}

Now any call using Enumeration class object will be calling Enum class methods, so acting as an adapter to Enum class, caller class doesnot know that it call is being transfered to Enum class.

Hope above example make sense, although if you have any query you can connect with me over comments or by any means.

Leave a Reply

Your email address will not be published. Required fields are marked *