美文网首页
责任链模式

责任链模式

作者: simplerandom | 来源:发表于2020-05-20 16:31 被阅读0次
    public class YuanGong {
        String name;
    
        int days;
    
        public YuanGong(String name, int days) {
            this.name = name;
            this.days = days;
        }
    
        public int getDays() {
            return days;
        }
    
        public void qinJia() {
            System.out.println(name + "被批准请假" + days + "天");
        }
    }
    
    public abstract class Leader {
        YuanGong yuanGong;
    
        Leader leader;
    
        public Leader(YuanGong yuanGong, Leader leader) {
            this.yuanGong = yuanGong;
            this.leader = leader;
        }
    
        abstract void approve();
    }
    
    public class ZhuZhang extends Leader {
    
        public ZhuZhang(YuanGong yuanGong, Leader higherleader) {
            super(yuanGong, higherleader);
        }
    
        @Override
        public void approve() {
            if (yuanGong.days <= 3) {
                yuanGong.qinJia();
                System.out.println("组长批准的");
            } else {
                leader.approve();
            }
        }
    }
    
    public class JingLi extends Leader {
    
        public JingLi(YuanGong yuanGong, Leader higherleader) {
            super(yuanGong, higherleader);
        }
    
        @Override
        public void approve() {
            if (yuanGong.days <= 5) {
                yuanGong.qinJia();
                System.out.println("经理批准的");
            } else {
                leader.approve();
            }
        }
    }
    
    public class LaoBan extends Leader {
    
        public LaoBan(YuanGong yuanGong, Leader higherleader) {
            super(yuanGong, higherleader);
        }
    
        @Override
        public void approve() {
            yuanGong.qinJia();
            System.out.println("老板批准的");
        }
    }
    

    测试

    public class Test {
        public static void main(String[] args) {
            YuanGong yuanGong1 = new YuanGong("张雨婷", 3);
            ZhuZhang zhuZhang = new ZhuZhang(yuanGong1, new JingLi(yuanGong1, new LaoBan(yuanGong1, null)));
            zhuZhang.approve();
            YuanGong yuanGong2 = new YuanGong("张雨婷", 8);
            ZhuZhang zhuZhang2 = new ZhuZhang(yuanGong2, new JingLi(yuanGong2, new LaoBan(yuanGong2, null)));
            zhuZhang2.approve();
        }
    }
    

    相关文章

      网友评论

          本文标题:责任链模式

          本文链接:https://www.haomeiwen.com/subject/cgsnohtx.html