概述
职责链模式 (Chain of Responsibility Pattern) 又称责任链模式。它将请求的发送者和接收者解耦,如果有多个接收者,将这些接收者连接成一条链,请求沿着这条链传递,直到被处理。
优点:降低耦合度,符合“开闭原则”。
缺点:请求不一定会被处理。链过长会造成性能问题。
class Request {
private String request;
public String getRequest() {
return request;
}
}
abstract class Handler {
protected Handler next;
protected setNext(Handler h) {
next = h;
}
abstract void deal(Request);
}
class HandlerA extends Handler {
public void deal(Request r) {
if (r == "a") {
//
} else if (this.next != null) {
this.next.deal(r);
}
}
}
class HandlerB extends Handler {
public void deal(Request r) {
if (r == "b") {
//
} else if (this.next != null) {
this.next.deal(r);
}
}
}
main() {
Handler a = new HandlerA();
Handler b = new HandlerB();
a.setNext(b);
Request r = new Request();
a.deal(r);
}
图示:
参考
[1]. 刘伟, 设计模式. 2011.
标签:15,职责,deal,void,Request,模式,next,Handler,class From: https://www.cnblogs.com/xdreamc/p/16462974.html