责任链模式:将能够处理同一类请求的对象连成一条链,如果不能处理则传递给链上的下一个对象。
//请假对象 public class QingjiaRequest { private String name; private int days; private String reason; public QingjiaRequest(String name, int days, String reason) { 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; } }
//抽象类 public abstract class Leader { String name; Leader nextLeader; public Leader(String name) { this.name = name; } public void setNextLeader(Leader nextLeader) { this.nextLeader = nextLeader; } //设置责任链的处理对象(核心) public abstract void handleRequest(QingjiaRequest qingjiaRequest); }
//主任 public class Zhuren extends Leader{ public Zhuren(String name){ super(name); } public void handleRequest(QingjiaRequest qingjiaRequest) { if(qingjiaRequest.getDays()<3){ System.out.println("员工请假小于3天"); System.out.println("审批通过"); }else{ if(this.nextLeader!=null){ this.nextLeader.handleRequest(qingjiaRequest); } } } }
//经理 public class Manager extends Leader{ public Manager(String name){ super(name); } public void handleRequest(QingjiaRequest qingjiaRequest) { if(qingjiaRequest.getDays()<10&&qingjiaRequest.getDays()>3){ System.out.println("经理审批通过"); }else{ //经理处理后的逻辑 } } }
public static void main(String[] args) { QingjiaRequest qingjiaRequest = new QingjiaRequest("张三", 2, "请假"); //QingjiaRequest qingjiaRequest1 = new QingjiaRequest("张三", 5, "请假"); Leader a = new Zhuren("张主任"); Leader b = new Manager("王经理"); //可以用一个容器对象责任链对象进行一些封装 a.setNextLeader(b); //开始请假 a.handleRequest(qingjiaRequest); }
应用场景:try catch,javascript 冒泡,servlet filter,struts2 拦截器
时间: 2024-10-19 20:23:15