责任链(Chain of Responsibility)模式
作者:互联网
名称:
责任链模式 (Chain of Responsibility Pattern)
问题:
The Chain of Responsibility pattern establishes a chain within a system, so that a message can either be handled at the level where it is first received, or be directed to an object that can handle it.
解决方案:
1、 模式的参与者
1、Handler
-定义一个处理请求的接口。
-(可选)实现后继链。
2、ConcreteHandler
-处理它所负责的请求。
-可访问它的后继者。
-如果可处理该请求,就处理之;否则将该请求转发给它的后继者。
3、Client
-向链上的具体处理者对象提交请求。
2.实现方式
abstract class Handler { private Handler next; public void setNext(Handler next) { this.next=next; } public Handler getNext() { return next; } public abstract void handleRequest(String request); }
class ConcreteHandler1 extends Handler { public void handleRequest(String request) { if(request.equals("Handler1")) { System.out.println("process on Handler1!"); } else { if(getNext()!=null) { getNext().handleRequest(request); } else { System.out.println("no processor"); } } } }
class ConcreteHandler2 extends Handler { public void handleRequest(String request) { if(request.equals("Handler2")) { System.out.println("process on Handler2!"); } else { if(getNext()!=null) { getNext().handleRequest(request); } else { System.out.println("no processor"); } } } }
参考资料
《设计模式:可复用面向对象软件的基础》
标签:getNext,Chain,request,next,责任,Handler,Responsibility,handleRequest,public 来源: https://www.cnblogs.com/diameter/p/13209221.html