责任链模式 Posted on 2021-02-23 | In 设计模式 z责任链模式: 新建请求 新建各级主管 新建各级主管建立链表 初级主管开始 判断能否处理 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118public class AbstractLeaveHandler { /**直接主管审批处理的请假天数*/ protected int MIN = 1; /**部门经理处理的请假天数*/ protected int MIDDLE = 3; /**总经理处理的请假天数*/ protected int MAX = 30; /**领导名称*/ protected String handlerName; /**下一个处理节点(即更高级别的领导)*/ protected AbstractLeaveHandler nextHandler; /**设置下一节点*/ protected void setNextHandler(AbstractLeaveHandler handler){ this.nextHandler = handler; } /**处理请假的请求,子类实现*/ protected void handlerRequest(LeaveRequest request){ }}//直接主管public class DirectLeaderLeaveHandler extends AbstractLeaveHandler{ public DirectLeaderLeaveHandler(String name) { this.handlerName = name; } @Override protected void handlerRequest(LeaveRequest request) { if(request.getLeaveDays() <= this.MIN){ System.out.println("直接主管:" + handlerName + ",已经处理;流程结束。"); return; } if(null != this.nextHandler){ this.nextHandler.handlerRequest(request); }else{ System.out.println("审批拒绝!"); } }}//部门经理public class DeptManagerLeaveHandler extends AbstractLeaveHandler{ public DeptManagerLeaveHandler(String name) { this.handlerName = name; } @Override protected void handlerRequest(LeaveRequest request) { if(request.getLeaveDays() >this.MIN && request.getLeaveDays() <= this.MIDDLE){ System.out.println("部门经理:" + handlerName + ",已经处理;流程结束。"); return; } if(null != this.nextHandler){ this.nextHandler.handlerRequest(request); }else{ System.out.println("审批拒绝!"); } }}//总经理public class GManagerLeaveHandler extends AbstractLeaveHandler{ public GManagerLeaveHandler(String name) { this.handlerName = name; } @Override protected void handlerRequest(LeaveRequest request) { if(request.getLeaveDays() > this.MIDDLE && request.getLeaveDays() <= this.MAX){ System.out.println("总经理:" + handlerName + ",已经处理;流程结束。"); return; } if(null != this.nextHandler){ this.nextHandler.handlerRequest(request); }else{ System.out.println("审批拒绝!"); } }}//请求public class LeaveRequest { //请求天数和名字 private int leaveDays; private String name;}//客户端public class ResponsibilityTest { public static void main(String[] args) { LeaveRequest request = LeaveRequest.builder().leaveDays(5).name("小明").build(); AbstractLeaveHandler directLeaderLeaveHandler = new DirectLeaderLeaveHandler("县令"); DeptManagerLeaveHandler deptManagerLeaveHandler = new DeptManagerLeaveHandler("知府"); GManagerLeaveHandler gManagerLeaveHandler = new GManagerLeaveHandler("京兆尹"); directLeaderLeaveHandler.setNextHandler(deptManagerLeaveHandler); deptManagerLeaveHandler.setNextHandler(gManagerLeaveHandler); directLeaderLeaveHandler.handlerRequest(request); }} Donate comment here Donate WeChat Pay