責任鏈模式(chain of responsibility)
阿新 • • 發佈:2018-01-10
機制 request chain pro over 過濾 攔截器 asc servlet開發
責任鏈模式定義:
將能夠處理同一類請求的對象連成一條鏈,所提及的請求沿著鏈傳遞,鏈上的對象逐個判斷是否有能力處理該請求,如果能則處理,如果不能則傳遞給鏈上的下一個對象。
責任鏈屬於行為型模式的一種。行為型模式關註系統中對象之間的相互交互,研究系統在運行時對象之間的相互通信和協作,進一步明確對象的職責。
下面使用公司請假的例子來說明:
創建請假請求者
package com.note.pattern.responsibility; public class LeaveRequest { private String name; private int days; private String reason; public LeaveRequest(String name, int days, String reason) { super(); this.name = name; this.days = days; this.reason = reason; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getDays() { return days; } public void setDays(int days) { this.days = days; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } }
創建Leader抽象類與不同級別的Leader作為實現子類,負責接收請假請求:
package com.note.pattern.responsibility; public abstract class Leader { protected String name; protected Leader nextLeader; //責任鏈上的後繼對象 public Leader(String name) { this.name = name; } //設定責任鏈上的後繼對象 public void setNextLeader(Leader leader) { nextLeader = leader; } /** * 處理請求的核心的業務方法 * @param request */ public abstract void handleRequest(LeaveRequest request); } /*** * 主任 */ class Director extends Leader { public Director(String name) { super(name); } @Override public void handleRequest(LeaveRequest request) { if(request.getDays() < 3) { System.out.println("員工:"+request.getName()+"請假,天數:"+request.getDays()+",理由:"+request.getReason()); System.out.println("主任:"+this.name+",審批通過!"); }else { nextLeader.handleRequest(request); } } } /** * 經理 */ class Manager extends Leader { public Manager(String name) { super(name); } @Override public void handleRequest(LeaveRequest request) { if(request.getDays() < 10) { System.out.println("員工:"+request.getName()+"請假,天數:"+request.getDays()+",理由:"+request.getReason()); System.out.println("經理:"+this.name+",審批通過!"); }else { nextLeader.handleRequest(request); } } } /** * 總經理 */ class GeneralManager extends Leader { public GeneralManager(String name) { super(name); } @Override public void handleRequest(LeaveRequest request) { if(request.getDays() < 30) { System.out.println("員工:"+request.getName()+"請假,天數:"+request.getDays()+",理由:"+request.getReason()); System.out.println("總經理:"+this.name+",審批通過!"); }else { System.out.println("莫非"+request.getName()+"想辭職,居然請假"+request.getDays()+"天!"); } } }
package com.note.pattern.responsibility; public class Client { public static void main(String[] args) { Leader a = new Director("張三"); Leader b = new Manager("李四"); a.setNextLeader(b); Leader c = new GeneralManager("王五"); b.setNextLeader(c); //開始請假操作 LeaveRequest req1 = new LeaveRequest("TOM", 25, "回英國老家探親!"); a.handleRequest(req1); } }
責任鏈模式在開發中的應用場景:
Java中異常機制就是一種責任鏈模式。一個try可以對應多個catch,當第一個catch不匹配類型,則自動跳到第二個catch;
javaScript中事件的冒泡和捕獲機制;
Servlet開發中過濾器的鏈式處理;
Struts2中攔截器的調用;
責任鏈模式(chain of responsibility)