感想
责任链模式:如果有多个对象都有机会处理请求,责任链可使请求的发送者和接收者解耦,请求沿着责任链传递,直到有一个对象处理了它为止。
责任链模式的优点:
- 将请求的发送者和接收者解耦,使多个对象都有机会处理这个请求。
- 可以简化对象,因为它无须知道链的结构。
- 可以动态地添加或删减处理请求的链结构。
责任链模式的缺点:
- 请求从链的开头进行遍历,对性能有一定的损耗。
- 并不保证请求一定被处理。
以下例子引用了磊_lei的例子:Java 设计模式(17) —— 责任链模式
a.定义采购对象:
1 | public class PurchaseRequest { |
b.定义决策者的抽象类:
1 | public abstract class Approver { |
c1.各决策者在自己的责任范围内实现责任方法,组长:
1 | public class GroupApprover extends Approver { |
c2.部门经理:
1 | public class DepartmentApprover extends Approver { |
c3.副经理:
1 | public class VicePresidentApprover extends Approver { |
c4.经理:
1 | public class PurchaseRequest { |
d.定义一个客户:
1 | public class Client { |
e.客户端使用:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23public class App {
public static void main(String[] args) {
Client mClient = new Client();
Approver GroupLeader = new GroupApprover("Tom");
Approver DepartmentLeader = new DepartmentApprover("Jerry");
Approver VicePresident = new VicePresidentApprover("Kate");
Approver President = new PresidentApprover("Bush");
//形成一个责任链的闭环
GroupLeader.SetSuccessor(DepartmentLeader);
DepartmentLeader.SetSuccessor(VicePresident);
VicePresident.SetSuccessor(President);
President.SetSuccessor(GroupLeader);
GroupLeader.ProcessRequest(mClient.sendRequst(1, 100, 40));
GroupLeader.ProcessRequest(mClient.sendRequst(2, 200, 40));
GroupLeader.ProcessRequest(mClient.sendRequst(3, 300, 40));
GroupLeader.ProcessRequest(mClient.sendRequst(4, 400, 140));
}
}