concept

Link objects that have the opportunity to process the same request into a chain, passing the request along the chain until the object processes it

Usage scenarios

Multiple objects can process the same request, but which object to process is determined dynamically at run time

implementation

  • Handler – Abstract Handler: this includes the method that intercepts the request (handleRequest), the method that actually processes the request after intercepting (Handle), and the reference field of the next processing node object (nextHandler), and the Handler’s level field (handlerLevel).
  • Handler1, Handler2 — concrete handler. Need to set the level, the next node object field, implement the Handle method
  • Request – The abstract requester, containing the processing object and the processing level
  • Request1, Request2 – the specific requester
public abstract class Handler{
    protected Handler nextHandler;

    public final void handleRequest(Request req){
        if(getHandlerLevel() == req.requestLevel){
            handle(req);
        } else {
            if(nextHandler ! = null){ nextHandler.handleRequest(req); }else {
                System.out.println("all the handle cannot handle the request");
            }
        }
    }

    protected abstract int getHandlerLevel();

    protected abstract void handle(Request req);   
}

public class Handler1 extends Handler {

    @Override
    protected int getHandlerLevel() {return 1;
    }

    @Override
    protected void handle (Request req){
        System.out.println("handler1 handle the request");
    }
}

public class Handler2 extends Handler {

    @Override
    protected int getHandlerLevel() {return 2;
    }

    @Override
    protected void handle (Request req){
        System.out.println("handler2 handle the request");
    }
}

public class Handler3 extends Handler {

    @Override
    protected int getHandlerLevel() {return 3;
    }

    @Override
    protected void handle (Request req){
        System.out.println("handler3 handle the request"); } } public abstract class Request { private Object obj; Public Request(Object obj){this.obj = obj; } public ObjectgetContent() {return obj;    
    }

    public abstract int getRequestLevel();
}

public class Request extends Request {
    public Request(Object obj){
        super(obj);
    }

    @Override
    public int getRequestLevel() {return 1;
    }
}

public class Request2 extends Request {
    public Request(Object obj){
        super(obj);
    }

    @Override
    public int getRequestLevel() {return 2;
    }
}


public class Client{
    public static void main(String[] args){
        Handler h1 = new Handler1();
        Handler h2 = new Handler2();
        Handler h3 = new Handler3();
        h1.nextHandler = h2;
        h2.nextHandler = h3;
        Request req = new Request2("Request2"); h1.handleRequest(req); }}Copy the code