Design Patterns Java - Chain of responsibility Php

1) What have we done?

As we said we bind "Handler" objects in chain.
And we pass request to first handler and we don't have to bother of "Request" anymore.


public abstract class Handler
{
    protected Handler next;

    public void setNext(Handler next)
    {
        this.next = next;
    }

    abstract void handleRequest(Request request);
}

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

        handlerA.handleRequest(request);
    }
}




2) Can we improve this?

Yes in "HandlerA" and "HandlerB" the code is duplicated let's try to eliminate this in step3

public class HandlerA extends Handler
{
    @Override
    public void handleRequest(Request request)
    {
        if (request.getAttribute().equals("handlerA"))
        {
            System.out.println("HandlerA doing something with request");
        }
        else if (next != null)
        {
            next.handleRequest(request);
        }
    }
}

public class HandlerB extends Handler
{
    @Override
    public void handleRequest(Request request)
    {
        if (request.getAttribute().equals("handlerB"))
        {
            System.out.println("HandlerB doing something with request");
        }
        else if (next != null)
        {
            next.handleRequest(request);
        }
    }
}