java设计模式之责任链模式

①UML设计:


②定义:职责链模式(称责任链模式)将请求的处理对象像一条长链一般组合起来,形成一条对象链。请求并不知道具体执行请求的对象是哪一个,这样就实现了请求与处理对象之间的解耦

③示例:
public abstract class Leader {
    private Leader nextLeader;

    public abstract void deal(Vocation vocation);

    public void setNextLeader(Leader leader) {
        this.nextLeader = leader;
    }

    public Leader getNextLeader() {
        return nextLeader;
    }
}

/**
 * 1天的假期由小组长审批
 */
public class GroupLeader extends Leader {

    private final int day = 1;

    @Override
    public void deal(Vocation vocation) {
        if (vocation.getDays() > day) {
            getNextLeader().deal(vocation);
        } else {
            System.out.println("GroupLeader deal the vocation for 1 day");
        }
    }
}
/**
 * 1~3天的假期有部门领导审批
 */
public class DepartmentLeader extends Leader {

    private final int days = 3;

    @Override
    public void deal(Vocation vocation) {
        if (vocation.getDays() > days) {
            getNextLeader().deal(vocation);
        } else {
            System.out.println("Department deal the vocation for more than 1-3 days");
        }
    }
}
/**
 * 3天以上的假期由主管审批
 */
public class GeneralLeader extends Leader {
    @Override
    public void deal(Vocation vocation) {
        System.out.println("GeneralLeader deal the vocation no matter how many days");
    }
}
public class Vocation {
    private int    days;

    private String reasons;

    public void setDays(int days) {
        this.days = days;
    }

    public int getDays() {
        return days;
    }

    public void setReasons(String reasons) {
        this.reasons = reasons;
    }

    public String getReasons() {
        return reasons;
    }
}
public class Client3 {
    public static void main(String[] args) {
        Vocation vocation = new Vocation();
        vocation.setDays(4);//设置不同的请假天数,不同的领导人会处理
        Leader gpLeader = new GroupLeader();
        Leader dmLeader = new DepartmentLeader();
        Leader gLeader = new GeneralLeader();
        gpLeader.setNextLeader(dmLeader);
        dmLeader.setNextLeader(gLeader);
        gpLeader.deal(vocation);//首先小组长先处理请求
    }
}




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值