• 设计模式(第十五式:责任链模式)


    概念:
      责任链模式:Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receivering objects and pass the request along the chain until an object handles it.使用多个对象都有机会处理请求,从而避免了请求的发送者和接受者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递请求,知道有对象处理它为止。

    实现:
      年级抽象类

    public abstract class Grade {
        private Grade grade;
        private String gradeName;
        private Integer score;
    
        public Grade getGrade() {
            return grade;
        }
    
        public void setGrade(Grade grade) {
            this.grade = grade;
        }
    
        public String getGradeName() {
            return gradeName;
        }
    
        public void setGradeName(String gradeName) {
            this.gradeName = gradeName;
        }
    
        public Integer getScore() {
            return score;
        }
    
        public void setScore(Integer score) {
            this.score = score;
        }
    
        public void upgrade() {
            System.out.println("上" + this.getGradeName());
    
            if (score < 60) {
                System.out.println("考试没通过,留级");
            } else {
                if (grade == null) {
                    System.out.println("考试通过,毕业");
                } else {
                    System.out.println("考试通过,升级");
                    grade.upgrade();
                }
    
            }
    
        }
    }

      具体年级实现

    public class FirstGrade extends Grade {
    }
    
    public class SecondGrade extends Grade {
    }
    ...


    测试及结果:

    @Test
    public void responsibilityChainTest(){
        Grade firstGrade = new FirstGrade();
        Grade secondGrade = new SecondGrade();
        firstGrade.setGrade(secondGrade);
        firstGrade.setGradeName("一年级");
        firstGrade.setScore(70);
        secondGrade.setScore(50);
        secondGrade.setGradeName("二年级");
        secondGrade.setGrade(null);
    
        firstGrade.upgrade();
    
    }


      上一年级
      考试通过,升级
      上二年级
      考试没通过,留级

    分析:
      1.有点类似递归的方式,所以效率上会有所损失。
      2.灵活性较高,可以比较方便的改变运行流程
      3.最常见的就是Struts2 请求中的拦截器链,就采用了这种设计模式

  • 相关阅读:
    June. 26th 2018, Week 26th. Tuesday
    June. 25th 2018, Week 26th. Monday
    June. 24th 2018, Week 26th. Sunday
    June. 23rd 2018, Week 25th. Saturday
    June. 22 2018, Week 25th. Friday
    June. 21 2018, Week 25th. Thursday
    June. 20 2018, Week 25th. Wednesday
    【2018.10.11 C与C++基础】C Preprocessor的功能及缺陷(草稿)
    June.19 2018, Week 25th Tuesday
    June 18. 2018, Week 25th. Monday
  • 原文地址:https://www.cnblogs.com/ben-mario/p/11133194.html
Copyright © 2020-2023  润新知