模拟实现类:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 *责任链模式: 将处理同一类事务的所有对象按次序连接在一起(就像连成一条锁链一样), 3 * 依次去处理待定事务,如果该对象处理不了,就传给其后的对象来处理 4 */ 5 public abstract class Leader { 6 public Leader(String name, Leader nextLeader){ 7 this.name = name; 8 this.nextLeader = nextLeader; 9 } 10 11 public void setNextLeader(Leader nextLeader){ 12 this.nextLeader = nextLeader; 13 } 14 15 public abstract void handleRequest(LeaveRequest request); 16 17 protected String name; 18 protected Leader nextLeader; 19 } 20 21 class Director extends Leader{ 22 public Director(String name, Leader nextLeader){ 23 super(name, nextLeader); 24 } 25 26 @Override 27 public void handleRequest(LeaveRequest request) { 28 if(request.getDay() <= 5){ 29 System.out.println(name + "Director: OK!"); 30 } else{ 31 if(nextLeader != null){ 32 nextLeader.handleRequest(request); 33 } 34 } 35 } 36 } 37 38 class Manager extends Leader{ 39 public Manager(String name, Leader nextLeader){ 40 super(name, nextLeader); 41 } 42 43 @Override 44 public void handleRequest(LeaveRequest request) { 45 if(request.getDay() <= 10){ 46 System.out.println(name + "Manager: OK!"); 47 } else{ 48 if(nextLeader != null){ 49 nextLeader.handleRequest(request); 50 } 51 } 52 } 53 } 54 55 class GeneralManager extends Leader{ 56 public GeneralManager(String name){ 57 super(name, null); 58 } 59 60 @Override 61 public void handleRequest(LeaveRequest request) { 62 System.out.println(name + "GeneralManager: OK!"); 63 } 64 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class LeaveRequest { 2 public LeaveRequest(String name, int day, String reason){ 3 this.name = name; 4 this.day = day; 5 this.reason = reason; 6 } 7 8 public String getName() { 9 return name; 10 } 11 12 public void setName(String name) { 13 this.name = name; 14 } 15 16 public int getDay() { 17 return day; 18 } 19 20 public void setDay(int day) { 21 this.day = day; 22 } 23 24 public String getReason() { 25 return reason; 26 } 27 28 public void setReason(String reason) { 29 this.reason = reason; 30 } 31 32 private String name; 33 private int day; 34 private String reason; 35 }
测试类:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Test{ 2 public static void main(String[] args){ 3 Leader leader1 = new GeneralManager("张三"); 4 Leader leader2 = new Manager("李四", leader1); 5 Leader leader3 = new Director("王五", leader2); 6 leader3.handleRequest(new LeaveRequest("小李", 7, "结婚")); 7 } 8 }