Design Patterns PHP - Visitor Java

1) What have we got?

We have couple of objects of type "CommonInterface". These objects are stored on some structure. It can be tree or list like in our example.


interface CommonInterface
{
    public function doCommonAction();
}

class ClassA implements CommonInterface
{
    public function doCommonAction()
    {
        echo 'ClassA doing common action' . PHP_EOL;
    }

    public function doA()
    {
        echo 'ClassA doing A action' . PHP_EOL;
    }
}

class ClassB
{
    public function doCommonAction()
    {
        echo 'ClassB doing common action' . PHP_EOL;
    }

    public function doB()
    {
        echo 'ClassB doing B action' . PHP_EOL;
    }
}




Although all objects are "CommonInterface" type they have implementations of different classes, like in our case "ClassA" and "ClassB"

2) What want we to do?

We want on whole structure call all specific operations for given types like here "ClassA" and "ClassB"

3) How do we do this?

In Client we traverse whole structure and depending on concrete implementation we call proper method.


foreach ($collection as $object) {
    if ($object instanceof ClassA)
        $object->doA();
    if ($object instanceof ClassB)
        $object->doB();
}




4) What are cons?

- Client need to know classes of implementation which are on the list
- It need to check this class and call proper methods, definitely it doesn't nice interface for client

5) What can we do?

We apply "Visitor" pattern - which has special adoption for execution specific tasks on diversified structure.

We create "Visitor" object and we define there what we want for concrete objects.