Design Patterns Java - Chain of responsibility Php

1) What have we at the beginning?

Let's imagine that we have object "Request" which need to be handled somehow.
We created interface "Handler" for this.


public class Request
{
    private String attribute;

    public Request(String attribute)
    {
        this.attribute = attribute;
    }

    public String getAttribute()
    {
        return attribute;
    }
}

public interface Handler
{
    void handleRequest(Request request);
}

public class HandlerA implements Handler
{
    @Override
    public void handleRequest(Request request)
    {
        System.out.println("HandlerA doing something with request");
    }
}

public class HandlerB implements Handler
{
    @Override
    public void handleRequest(Request request)
    {
        System.out.println("HandlerB doing something with request");
    }
}




2) What are we doing in client?

Depending on "attribute" field of Request we choose which "Handler" has to service this request.


public class Client
{
    public Client(Request request)
    {
        Handler handlerA = new HandlerA();
        Handler handlerB = new HandlerB();

        if (request.getAttribute().equals("handlerA"))
        {
            handlerA.handleRequest(request);
        }
        else
        {
            handlerB.handleRequest(request);
        }
    }
}




3) What are cons?

We want to simplify "Client" we don't want to make "Client" to check "attribute"

Can be more than two "Handler" objects and check "Request" objects shouldn't be responsible of "Client"

4) What can we do?

We apply "ChainOfResponsibility" pattern so:

1) We bind "Handlers" in chain
2) In "Handler" we check if this handler can service "Request"
3) If yes let's service "Request"
4) If not pass "Request" to next "Handler"

Let's see this in step2