设计模式(第二十二式:状态模式)

概念:
  状态模式:Allow an object to alter its benhavior when its internal state changes. The object will appear to change its class. 当一个对象内在状态改变是允许改变行为,这个对象看起来像改变了其类型。

实现:
  定义状态接口或抽象状态类

    public abstract class AbstractCourse {
        public AbstractCourse(String teacherName) {
            this.teacherName = teacherName;
        }

        private String teacherName;

        public abstract void study();

        public String getTeacherName() {
            return teacherName;
        }

        public void setTeacherName(String teacherName) {
            this.teacherName = teacherName;
        }
    }


  状态具体实现

    public class BiologyClass extends AbstractCourse {

        public BiologyClass(String teacherName) {
            super(teacherName);
        }

        @Override
        public void study() {
            System.out.println(this.getTeacherName() + "正在上生物课");
        }
    }

 

    public class MathClass extends AbstractCourse {

        public MathClass(String teacherName) {
            super(teacherName);
        }

        @Override
        public void study() {
            System.out.println(this.getTeacherName() + "正在上数学课");
        }
    }

 


  具体应用场景

    public class School {
        private AbstractCourse math = new MathClass("数学老师");
        private AbstractCourse biology = new BiologyClass("生物老师");

        private AbstractCourse now;

        public void study(){
            now.study();
        }

        public AbstractCourse getMath() {
            return math;
        }

        public void setMath(AbstractCourse math) {
            this.math = math;
        }

        public AbstractCourse getBiology() {
            return biology;
        }

        public void setBiology(AbstractCourse biology) {
            this.biology = biology;
        }

        public AbstractCourse getNow() {
            return now;
        }

        public void setNow(AbstractCourse now) {
            this.now = now;
        }
    }


测试及结果:

    public class StateTest {

        @Test
        public void statetest(){
            School school = new School();
            school.setNow(school.getMath());
            school.study();

            school.setNow(school.getBiology());
            school.study();
        }
    }


  数学老师正在上数学课
  生物老师正在上生物课
分析:
  1.状态过多会导致子类过多。
  2.封装性好,在不改变应用场景的情况下,实际上是改变了使用的不同类,但是对外外部而言是种改变了其中的属性(状态)。

posted @ 2019-07-04 18:15  Mario0315  阅读(185)  评论(0编辑  收藏  举报