您的位置:首页 > 大数据 > 人工智能

职责链模式(Chain of Responsibility)

2014-09-08 11:25 316 查看
职责链模式的意图:使多个对象都有机会处理请求,避免请求发送者和接受者之间的高耦合关系;将这些接受者连成一条链,将请求沿着这条链传递下去,直到有一个对象处理它为止

该模式的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. 客户端和接受者代码的松耦合,因为对于客户端来说,该职责链中只需要有一个节点能够处理其请求即可,不要求客户端显式指定接受者

注意:对于职责链模式需要注意的一点是确保客户端的请求能够被其中某个节点处理
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: