什么是责任链模式?
每个对象以链的方式进行连接,上级对象关联下级对象,一级一级的向下运行,直到运行到最后一个对象结束。
示例场景描述
某公司普通职员请假,申请请假后需要通过组长审批 项目经理审批 人事主管审批同意后才能请假成功。
示例图
image.png示例代码
1.创建请假抽象对象LeaveBehaviour(抽象出请假的行为)
public abstract class LeaveBehaviour {
protected LeaveBehaviour nextleaveBehaviour;
protected abstract void leave();
public void setNextLeave(LeaveBehaviour nextleaveBehaviour){
this.nextleaveBehaviour = nextleaveBehaviour;
}
}
2.创建组长实现类GroupLeader 经理实现类Manager 人事实现类PersonnelMatters
public class GroupLeader extends LeaveBehaviour{
@Override
protected void leave() {
System.out.println("组长审批请假信息:同意");
this.nextleaveBehaviour.leave();
}
}
public class Manager extends LeaveBehaviour {
@Override
protected void leave() {
System.out.println("经理审批请假信息:同意");
this.nextleaveBehaviour.leave();
}
}
public class PersonnelMatters extends LeaveBehaviour {
@Override
protected void leave() {
System.out.println("人事审批请假信息:同意");
}
}
3.运行类Test
public class Test {
public static void main(String[] args) {
GroupLeader groupLeader = new GroupLeader();
Manager manager = new Manager();
PersonnelMatters personnelMatters = new PersonnelMatters();
groupLeader.setNextLeave(manager);
manager.setNextLeave(personnelMatters);
groupLeader.leave();
}
}
4.运行结果
image.png
网友评论