Design Patterns Java - Visitor Php

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.


public interface CommonInterface
{
    void doCommonAction();
}

public class ClassA implements CommonInterface
{
    @Override
    public void doCommonAction()
    {
        System.out.println("ClassA doing common");
    }

    public void doA()
    {
        System.out.println("ClassA doing A");
    }
}

public class ClassB implements CommonInterface
{
    @Override
    public void doCommonAction()
    {
        System.out.println("ClassB doing common");
    }

    public void doB()
    {
        System.out.println("ClassB doing B");
    }
}




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.


import java.util.List;

public class Client
{
    public void traverseCollection(List<CommonInterface> collection)
    {
        collection.stream().forEach((s) -> {
            if (s instanceof ClassA)
                ((ClassA) s).doA();
            if (s instanceof ClassB)
                ((ClassB) s).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.