标签:
责任链模式定义:使多个对象都有机会处理请求,从而避免了请求的发送者和接受者的耦合关系。
举个栗子:在公司OA系统中申请一个办公用品,可能需要项目经理或部门经理或总经理批准.
具体由谁来批准时办公用品的分类决定.以下用代码方式实现
代码清单-1 抽象的处理者
public abstract class Handler { private Handler nextHandler; private String handlerName; //处理者的名字 public Handler(String handlerName) { this.handlerName = handlerName; } public final String HandleMesssage(OfficeSuppliesApply apply){ String result = null; //判断处理者是否有处理权限 if(this.getHandlerLevel() == apply.getApply_level()){ result = this.handleApply(apply); System.out.println(handlerName+":"+result); }else{ result = this.nextHandler.HandleMesssage(apply); //此处省略未匹配到处理等级的情况 } return result; } //设置下一个处理者 public void setNextHandler(Handler nextHandler) { this.nextHandler = nextHandler; } //每个处理者都有一个处理级别 protected abstract int getHandlerLevel(); //每个处理者必须实现处理任务 protected abstract String handleApply(OfficeSuppliesApply apply); }
代码清单-2 具体处理者
/** * 具体处理者 : 经理 */ public class Manager extends Handler { private int handlerLevel ; public Manager(int handlerLevel, String handlerName) { super(handlerName); this.handlerLevel = handlerLevel; } @Override protected int getHandlerLevel() { return handlerLevel; } @Override protected String handleApply(OfficeSuppliesApply apply) { String result = "通过"+apply.getSupplies_name()+"的申请!"; return result; } }
代码清单-3 办公用品申请
/** * 办公用品申请 */ public class OfficeSuppliesApply { //申请等级 private int apply_level ; //办公用品名称 private String supplies_name; public OfficeSuppliesApply(int apply_level , String supplies_name){ this.apply_level = apply_level; this.supplies_name = supplies_name; } public int getApply_level() { return apply_level; } public String getSupplies_name() { return supplies_name; } }
代码清单-4 场景类
public class Client { public static void main(String[] args) { Manager projectManger = new Manager(1,"项目经理"); Manager departMange = new Manager(2,"部门经理"); Manager topManager = new Manager(3,"总经理"); //处理顺序:项目经理 => 部门经理 => 总经理 projectManger.setNextHandler(departMange); departMange.setNextHandler(topManager); //申请一盒水笔 OfficeSuppliesApply pensApply = new OfficeSuppliesApply(1,"请求一盒水笔"); //申请一个台笔记本电脑 OfficeSuppliesApply notbookPcApply = new OfficeSuppliesApply(2,"请求一台笔记本电脑"); //申请一台投影仪 OfficeSuppliesApply projectorsApply = new OfficeSuppliesApply(3,"请求一台投影仪"); projectManger.HandleMesssage(pensApply); projectManger.HandleMesssage(notbookPcApply); projectManger.HandleMesssage(projectorsApply); } }
执行结果
项目经理:通过请求一盒水笔的申请! 部门经理:通过请求一台笔记本电脑的申请! 总经理:通过请求一台投影仪的申请!
责任链模式总结
优点:处理者和请求分开,两者解耦,提高系统的灵活性。
缺点:性能问题,每个请求都是从链头遍历到链尾,类似递归的方式,调试逻辑时可能比较复杂.
标签:
原文地址:http://www.cnblogs.com/taoyong/p/5648602.html