问题
Sunny软件公司的OA系统需要提供一个假条审批模块:如果员工请假天数小于3天,主任可以审批该假条;如果员工请假天数大于等于3天,小于10天,经理可以审批;如果员工请假天数大于等于10天,小于30天,总经理可以审批;如果超过30天,总经理也不能审批,提示相应的拒绝信息。试用职责链模式设计该假条审批模块。
package com.liyajie.test.ChainOfResponsibilityPattern;
/**
* 领导的抽象类,所有领导均需继承该类
* @author 李亚杰
* @date 2024/4/17 14:33
* @description Leadership
*/
public abstract class Leadership {
protected Leadership next;
protected String name;
protected Leadership(String name){
this.name = name;
}
protected void setNext(Leadership leadership){
this.next = leadership;
}
abstract protected void handle(Leave leave);
}
package com.liyajie.test.ChainOfResponsibilityPattern;
/**
* @author 李亚杰
* @date 2024/4/17 14:39
* @description Director
*/
public class Director extends Leadership{
public Director(String name) {
super(name);
}
@Override
protected void handle(Leave leave) {
if (leave.getDays()<3){
System.out.println("主任已审批:"+leave.getName()+"请假天数:"+leave.getDays());
return;
}
next.handle(leave);
}
}
package com.liyajie.test.ChainOfResponsibilityPattern;
/**
* @author 李亚杰
* @date 2024/4/17 14:44
* @description Manger
*/
public class Manger extends Leadership{
public Manger(String name) {
super(name);
}
@Override
protected void handle(Leave leave) {
if (leave.getDays()<10){
System.out.println("经理已审批:"+leave.getName()+"请假天数:"+leave.getDays());
return;
}
next.handle(leave);
}
}
package com.liyajie.test.ChainOfResponsibilityPattern;
/**
* @author 李亚杰
* @date 2024/4/17 14:47
* @description ManagingDirector
*/
public class ManagingDirector extends Leadership{
public ManagingDirector(String name) {
super(name);
}
@Override
protected void handle(Leave leave) {
if (leave.getDays()<30){
System.out.println("总经理已审批:"+leave.getName()+"请假天数:"+leave.getDays());
return;
}
System.out.println("总经理已拒绝审批:"+leave.getName()+"请假天数:"+leave.getDays());
System.out.println("请假失败");
}
}
package com.liyajie.test.ChainOfResponsibilityPattern;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* 请假类
* @author 李亚杰
* @date 2024/4/17 14:34
* @description Leave
*/
@Data
@AllArgsConstructor
public class Leave {
private String name;
private int days;
private boolean state;
}
package com.liyajie.test.ChainOfResponsibilityPattern;
/**
* @author 李亚杰
* @date 2024/4/17 14:49
* @description Clint
*/
public class Clint {
public static void main(String[] args) {
Leadership l1,l2,l3;
l1 = new Director("主任");
l2 = new Manger("经理");
l3 = new ManagingDirector("总经理");
l1.setNext(l2);
l2.setNext(l3);
Leave leave = new Leave("张三", 2, false);
Leave leave2 = new Leave("张三2", 20, false);
Leave leave3 = new Leave("张三3", 8, false);
Leave leave4 = new Leave("张三4", 211, false);
l1.handle(leave);
l1.handle(leave2);
l1.handle(leave3);
l1.handle(leave4);
}
}
通过使用职责链设计模式解决请假问题,spring的请求过滤器也是采用类似设计。