1、责任链模式介绍:
责任链模式是行为型设计模式之一;
2、责任链模式的定义:
使多个对象都有机会处理请求, 从而避免了请求的发送者和接收者之间的耦合关系, 将这些对象连成一条链, 并沿着这条链传递该请求, 直到有对象处理它为止;
3、责任链模式的使用场景:
(1) 多个对象可以处理同一请求, 但具体由哪个对象处理则在运行时动态决定;
(2) 在请求处理者不明确的情况下向多个对象中的一个提交一个请求;
(3) 需要动态指定一组对象处理请求;
4、示例代码:
public abstract class Leader {
protected Leader nextHandler;
public final void handleRequest(int money) {
if (money <= limit) {
handle(money);
} else {
if (null != nextHandler){
nextHandler.handleRequest(money);
}
}
}
public abstract int limit();
public abstract void handle(int money);
}
public class GroupLeader extends Leader {
@Override
public int limit() {
return 1000;
}
@Override
public void handle(int money) {
System.out.println("组长批复报销" + money + "元");
}
}
public class Director extends Leader {
@Override
public int limit() {
return 5000;
}
@Override
public void handle(int money) {
System.out.println("主管批复报销" + money + "元");
}
}
public class Manager extends Leader {
@Override
public int limit() {
return 10000;
}
@Override
public void handle(int money) {
System.out.println("经理批复报销" + money + "元");
}
}
public class Boss extends Leader {
@Override
public int limit() {
return Integer.MAX_VALUE;
}
@Override
public void handle(int money) {
System.out.println("老板批复报销" + money + "元");
}
}
public class XiaoMin {
public static void main(String[] args) {
GroupLeader groupLeander = new GroupLeader();
Director director = new Director();
Manager manager = new Manager();
Boss boss = new Boss();
nextHandler.handle = director;
director.handle = manager;
manager.handle = boss;
groupLeander.handleRequest(50000);
}
}
网友评论