职责链模式(Chain of Responsibility)
2014-09-08 11:25
316 查看
职责链模式的意图:使多个对象都有机会处理请求,避免请求发送者和接受者之间的高耦合关系;将这些接受者连成一条链,将请求沿着这条链传递下去,直到有一个对象处理它为止
该模式的UML图如下:
Handler:包含接受者的统一处理方法声明handlerequest(),其中也可以添加sucessor字段,用于指定其后继者(在Java中,此时Handler为抽象类;当它为接口时,由于接口中不能包含字段,所以不能指定后继者)
ConcreteHandler:具体的请求处理者(接受者),实现Handler中声明的handlerrequest方法,当它不能处理当前请求时,发送给他的后继者处理
下面看一个示例代码:
1. 各个接受者的职责明确,不会造成把所有逻辑堆在一个类中导致维护困难;在职责链模式中,需要增加逻辑只需要在链表中加一个节点即可
2. 客户端和接受者代码的松耦合,因为对于客户端来说,该职责链中只需要有一个节点能够处理其请求即可,不要求客户端显式指定接受者
注意:对于职责链模式需要注意的一点是确保客户端的请求能够被其中某个节点处理
该模式的UML图如下:
Handler:包含接受者的统一处理方法声明handlerequest(),其中也可以添加sucessor字段,用于指定其后继者(在Java中,此时Handler为抽象类;当它为接口时,由于接口中不能包含字段,所以不能指定后继者)
ConcreteHandler:具体的请求处理者(接受者),实现Handler中声明的handlerrequest方法,当它不能处理当前请求时,发送给他的后继者处理
下面看一个示例代码:
abstract class Doctor{ protected Doctor nextDoctor; public void setNextDoctor(Doctor next){ nextDoctor = next; } public abstract void handlePatient(String patient); } class SurfaceDoctor extends Doctor { @Override public void handlePatient(String patient) { if(patient == null){ System.out.println("Patient is null"); } if(patient != null && patient.equals("Surface")){ System.out.println("Patient is handled by SurfaceDoctor"); } else{ nextDoctor.handlePatient(patient); } } } class HeartDoctor extends Doctor { @Override public void handlePatient(String patient) { if(patient == null){ System.out.println("Patient is null"); } if(patient != null && patient.equals("Heart")){ System.out.println("Patient is handled by HeartDoctor"); } else{ nextDoctor.handlePatient(patient); } } } public class ChainOfResponsibility { public static void main(String[] args){ Doctor d1 = new SurfaceDoctor(); Doctor d2 = new HeartDoctor(); d1.setNextDoctor(d2); d1.handlePatient("Heart"); } }职责链模式的好处是:
1. 各个接受者的职责明确,不会造成把所有逻辑堆在一个类中导致维护困难;在职责链模式中,需要增加逻辑只需要在链表中加一个节点即可
2. 客户端和接受者代码的松耦合,因为对于客户端来说,该职责链中只需要有一个节点能够处理其请求即可,不要求客户端显式指定接受者
注意:对于职责链模式需要注意的一点是确保客户端的请求能够被其中某个节点处理
相关文章推荐
- 设计模式与泡mm的关系之Chain of Responsibility职责链模式及再思考
- Core Design Patterns(16) Chain of Responsibility 职责链模式
- 设计模式之Chain of Responsibility(职责链)
- 设计模式—Chain of Responsibility职责链模式
- C#面向对象设计模式纵横谈 学习笔记20 Chain of Responsibility职责链模式(行为型模式)
- 设计模式之Chain of Responsibility职责链模式
- 职责链模式(Chain of Responsibility)
- [导入]C#面向对象设计模式纵横谈(20):(行为型模式) Chain Of Responsibility 职责链模式.zip(8.18 MB)
- 设计模式之Chain of Responsibility(职责链)
- 设计模式学习笔记--Chain Of Responsibility 职责链模式
- 设计模式(17)-职责链模式(Chain of Responsibility)
- 职责链模式(chain of responsibility)解析例子 推荐
- 设计模式之职责链(chain of responsibility)---对象行为型模式
- [导入]C#面向对象设计模式纵横谈(14):Chain of Responsibility 职责链模式(行为型模式).zip(9.54 MB)
- 设计模式之Chain of Responsibility(职责链)
- Java设计模式-----Chain of Responsibility职责链模式
- 设计模式之Chain of Responsibility(职责链)
- 设计模式之Chain of Responsibility(职责链)
- 重温设计模式(三)——职责链模式(chain of responsibility)
- 设计模式--Chain Of Responsibility 职责链模式