行为类模式(一):职责链(Chain Of Responsibility)
2016-10-27 14:39
579 查看
定义
使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
UML
public class Main { public static void main(String[] args) { Handler h1 = new ProjectManager(); Handler h2 = new DepManager(); Handler h3 = new GeneralManager(); h1.setSuccessor(h2); h2.setSuccessor(h3); System.out.println(h1.handlerFeeRequest("小李", 300)); System.out.println(h1.handlerFeeRequest("小张", 300)); System.out.println(h1.handlerFeeRequest("小李", 800)); System.out.println(h1.handlerFeeRequest("小张", 800)); System.out.println(h1.handlerFeeRequest("小李", 3000)); System.out.println(h1.handlerFeeRequest("小张", 3000)); } /** * 责任处理对象 */ public static abstract class Handler { /** * 下一个处理请求的处理对象 */ protected Handler successor; /** * 设置下一个处理对象 */ public void setSuccessor(Handler successor) { this.successor = successor; } /** * 处理聚餐费用的请求 */ public abstract String handlerFeeRequest(String name, double fee); } public static class ProjectManager extends Handler { @Override public String handlerFeeRequest(String name, double fee) { String str = ""; if(fee < 500) { //小于500元的可以处理 if("小李".equals(name)) { str = "项目经理同意" + name + "的聚餐费用" + fee + "元的请求"; } else { str = "项目经理不同意" + name + "的聚餐费用" + fee + "元的请求"; } } else { if(this.successor != null) { return this.successor.handlerFeeRequest(name, fee); } } return str; } } public static class DepManager extends Handler { @Override public String handlerFeeRequest(String name, double fee) { String str = ""; if(fee < 1000) { //小于1000元的可以处理 if("小李".equals(name)) { str = "部门经理同意" + name + "的聚餐费用" + fee + "元的请求"; } else { str = "部门经理不同意" + name + "的聚餐费用" + fee + "元的请求"; } } else { if(this.successor != null) { return this.successor.handlerFeeRequest(name, fee); } } return str; } } public static class GeneralManager extends Handler { @Override public String handlerFeeRequest(String name, double fee) { String str = ""; //可以处理任意金额 if("小李".equals(name)) { str = "总经理同意" + name + "的聚餐费用" + fee + "元的请求"; } else { str = "总经理不同意" + name + "的聚餐费用" + fee + "元的请求"; } return str; } } }
View Code
相关文章推荐
- 【设计模式学习笔记十四】【行为模式】【职责链模式(Chain Of Responsibility)】
- 设计模式 ( 十二 ) 职责链模式(Chain of Responsibility)(对象行为
- 设计模式 ( 十二 ) 职责链模式(Chain of Responsibility)(对象行为)
- 行为模式:Chain Of Responsibility(职责链)
- 【设计模式基础】行为模式 - 3 - 职责链(Chain of responsibility)
- 设计模式:行为模式:职责链(chain of responsibility)
- 【设计模式】行为模式之Chain of Responsibility职责链
- 设计模式 ( 十二 ) 职责链模式(Chain of Responsibility)(对象行为)
- 设计模式 ( 十二 ) 职责链模式(Chain of Responsibility)(对象行为
- 设计模式 ( 十二 ) 职责链模式(Chain of Responsibility)(对象行为
- 设计模式 ( 十二 ) 职责链模式(Chain of Responsibility)(对象行为)
- 行为模式之Chain of Responsibility(职责链)
- 设计模式--Chain Of Responsibility 职责链模式
- 设计模式之Chain of Responsibility(职责链)
- 设计模式学习笔记--Chain Of Responsibility 职责链模式
- 设计模式学习笔记(十五)——Chain Of Responsibility职责链
- [导入]C#面向对象设计模式纵横谈(20):(行为型模式) Chain Of Responsibility 职责链模式.zip(8.18 MB)
- 设计模式—Chain of Responsibility职责链模式
- 职责链模式(Chain of Responsibility)
- 设计模式之Chain of Responsibility(职责链)