实际项目-审批流程的实现
程序员文章站
2024-02-14 15:05:40
...
1.需求
2.前言
我们可以快速的实现该工作审批流程,比如通过多个if-else去判断,但是当我们审批对象发生改变了,那我们的代码又需要去改动,破坏了软件的开闭原则。所以这里我们用一种行为设计模式:责任链模式。
3.Java代码具体实现
LeaveRequest.java
package com.cxx.chainOfResp;
/**
* 封装请假的基本信息
* @Author: cxx
* @Date: 2018/7/10 23:46
*/
public class LeaveRequest {
private String name;//请假人姓名
private int days;//请假天数
private String reason;//请假原因
public LeaveRequest(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;
}
}
Leader.java
package com.cxx.chainOfResp;
/**
* 抽象类
* @Author: cxx
* @Date: 2018/7/10 23:47
*/
public abstract class Leader {
protected String name;
protected Leader nextLeader;//责任链后期对象
public Leader(){
}
public Leader(String name){
super();
this.name=name;
}
public void setNextLeader(Leader nextLeader) {
this.nextLeader = nextLeader;
}
//处理请求核心业务方法
public abstract void handleRequest(LeaveRequest leaveRequest);
}
Director.java
package com.cxx.chainOfResp;
/**
* 主任
* @Author: cxx
* @Date: 2018/7/10 23:51
*/
public class Director extends Leader {
public Director(String name){
super(name);
}
@Override
public void handleRequest(LeaveRequest leaveRequest) {
if (leaveRequest.getDays()<3){
//处理
System.out.println("主任审批通过...");
}else {
//处理不了,给下处理
this.nextLeader.handleRequest(leaveRequest);
}
}
}
Manager.java
package com.cxx.chainOfResp;
/**
* 经理 处理3-10天请假
* @Author: cxx
* @Date: 2018/7/10 23:54
*/
public class Manager extends Leader{
public Manager(String name){
super(name);
}
@Override
public void handleRequest(LeaveRequest leaveRequest) {
if (leaveRequest.getDays()>3&&leaveRequest.getDays()<=10){
System.out.println("经理审批成功");
}else {
this.nextLeader.handleRequest(leaveRequest);
}
}
}
GeneralManager.java
package com.cxx.chainOfResp;
/**
* 总经理 10-30天
* @Author: cxx
* @Date: 2018/7/10 23:56
*/
public class GeneralManager extends Leader {
public GeneralManager(String name){
super(name);
}
@Override
public void handleRequest(LeaveRequest leaveRequest) {
if (leaveRequest.getDays()<30){
System.out.println("总经理审批通过...");
}else {
System.out.println(leaveRequest.getName()+":想辞职吧!");
}
}
}
测试类
package com.cxx.chainOfResp;
/**
* 测试 请假审批流程
* @Author: cxx
* @Date: 2018/7/10 23:58
*/
public class ChainTest {
public static void main(String[] args) {
Leader a = new Director("主任");
Leader b = new Manager("经理");
Leader c = new GeneralManager("总经理");
//责任链对象关系
a.setNextLeader(b);
b.setNextLeader(c);
//测试
LeaveRequest request = new LeaveRequest("cxx",2,"回家看病");
a.handleRequest(request);
}
}