按照我的理解,责任链就是每个对象都含有自己下一个对象的引用.
当一个对象请求的时候,会根据要求找到正确的对象.
public interface ILeave { String getName();//请假人姓名 int getNum();//请假天数 String getContent();//请假条内容 }
请假条抽象
public class Leave implements ILeave{ private String name;//姓名 private int num;//请假天数 private String content;//请假内容 public Leave(String name, int num, String content) { this.name = name; this.num = num; this.content = content; } public String getName() { return name; } public int getNum() { return num; } public String getContent() { return content; } }
public abstract class Handler { protected final static int NUM_ONE = 1; protected final static int NUM_THREE = 3; protected final static int NUM_SEVEN = 7; //该领导处理的请假天数区间 private int numStart = 0; private int numEnd = 0; //领导上面还有领导 private Handler nextHandler; //设置请假天数范围 上不封顶 public Handler(int numStart) { this.numStart = numStart; } //设置请假天数范围 public Handler(int numStart, int numEnd) { this.numStart = numStart; this.numEnd = numEnd; } //设置上级领导 public void setNextHandler(Handler nextHandler){ this.nextHandler = nextHandler; } //提交请假条 public final void submit(ILeave leave){ if(0 == this.numStart){ return; } //如果请假天数达到该领导者的处理要求 if(leave.getNum() >= this.numStart){ this.handleLeave(leave); //如果还有上级 并且请假天数超过了当前领导的处理范围 if(null != this.nextHandler && leave.getNum() > numEnd){ this.nextHandler.submit(leave);//继续提交 } } } //各级领导处理请假条方法 protected abstract void handleLeave(ILeave leave); }
处理者抽象
public class GroupLeader extends Handler { public GroupLeader() { //小组长处理1-3天的请假 super(Handler.NUM_ONE, Handler.NUM_THREE); } @Override protected void handleLeave(ILeave leave) { System.out.println(leave.getName() + "请假" + leave.getNum() + "天," + leave.getContent() + "。"); System.out.println("小组长审批:同意。"); } }
小组长
public class Manager extends Handler { public Manager() { //部门经理处理3-7天的请假 super(Handler.NUM_THREE, Handler.NUM_SEVEN); } @Override protected void handleLeave(ILeave leave) { System.out.println(leave.getName() + "请假" + leave.getNum() + "天," + leave.getContent() + "。"); System.out.println("部门经理审批:同意。"); } }
部门经理
public class BigManager extends Handler { public BigManager() { //部门经理处理7天以上的请假 super(Handler.NUM_SEVEN); } @Override protected void handleLeave(ILeave leave) { System.out.println(leave.getName() + "请假" + leave.getNum() + "天," + leave.getContent() + "。"); System.out.println("总经理审批:同意。"); } }
总经理
public static void main(String[] args) { //请假条来一张 ILeave leave = new Leave("小花",5,"身体不适"); //各位领导 Handler groupLeader = new GroupLeader(); Handler manager = new Manager(); Handler bigManager = new BigManager(); groupLeader.setNextHandler(manager);//小组长的领导是部门经理 manager.setNextHandler(bigManager);//部门经理的领导是总经理 //之所以在这里设置上级领导,是因为可以根据实际需求来更改设置,如果实战中上级领导人都是固定的,则可以移到领导实现类中。 //提交申请 groupLeader.submit(leave); }
客户端