把请求从链中的一个对象传到下一个对象,直到请求被响应为止。通过这种方式去除对象之间的耦合。
package com.strife.pattern.chain;
/**
* 职责链模式
*
* @author mengzhenghao
* @date 2022/6/6
*/
public class ChainCode {
public static void main(String[] args) {
AbstractAuditHandler projectHandler = new ProjectManger();
AbstractAuditHandler deptHandler = new DeptManger();
AbstractAuditHandler ceoHandler = new CeoManger();
projectHandler.setSuccessor(deptHandler);
deptHandler.setSuccessor(ceoHandler);
projectHandler.handleLeaveDay("zhangsan", 7);
}
}
abstract class AbstractAuditHandler {
/** 只有下一个处理请求的对象 */
protected AbstractAuditHandler successor = null;
public AbstractAuditHandler getSuccessor() {
return successor;
}
public void setSuccessor(AbstractAuditHandler successor) {
this.successor = successor;
}
/** 请假天数审批 */
public abstract void handleLeaveDay (String user,Integer day);
}
/** 项目经理审批 */
class ProjectManger extends AbstractAuditHandler {
@Override
public void handleLeaveDay(String user, Integer day) {
if (day <= 3){
System.out.println("项目经理审批:同意【"+user+"】,请假【"+day+"】天");
} else {
System.out.println("项目经理无权审批");
if (getSuccessor() != null){
getSuccessor().handleLeaveDay(user,day);
}
}
}
}
/**部门经理审批 */
class DeptManger extends AbstractAuditHandler{
@Override
public void handleLeaveDay(String user, Integer day) {
if (day > 3 && day <= 5){
System.out.println("部门经理审批:同意【"+user+"】,请假【"+day+"】天");
} else {
System.out.println("部门经理无权审批");
if (getSuccessor() != null){
getSuccessor().handleLeaveDay(user,day);
}
}
}
}
/** CEO审批 */
class CeoManger extends AbstractAuditHandler{
@Override
public void handleLeaveDay(String user, Integer day) {
if (day > 5){
System.out.println("CEO审批:同意【"+user+"】,请假【"+day+"】天");
} else {
if (getSuccessor() != null){
getSuccessor().handleLeaveDay(user,day);
}
}
}
}