zoukankan      html  css  js  c++  java
  • 状态模式-State Pattern(Java实现)

    状态模式-State Pattern

    在状态模式(State Pattern)中,类的行为是基于它的状态改变的。当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。

    State接口

    表明状态, 实体类是根据状态的变化而发生响应行为的变化的.

    /**
     * 状态抽象定义
     */
    public interface State {
    
        void onEnterState();
    
        void observe();
    
    }

    AngryState类

    状态的一种实现.

    /**
     * 生气状态
     */
    public class AngryState implements State {
    
        private Mammoth mammoth;
    
        public AngryState(Mammoth mammoth) {
            this.mammoth = mammoth;
        }
    
        @Override
        public void observe() {
            System.out.printf("%s 处于暴躁状态!
    ", mammoth);
        }
    
        @Override
        public void onEnterState() {
            System.out.printf("%s 开始生气了!
    ", mammoth);
        }
    }

    PeacefulState类

    状态的一种实现.

    /**
     * 平静状态
     */
    public class PeacefulState implements State {
    
        private Mammoth mammoth;
    
        public PeacefulState(Mammoth mammoth) {
            this.mammoth = mammoth;
        }
    
        @Override
        public void observe() {
            System.out.printf("%s 现在很平静.
    ", mammoth);
        }
    
        @Override
        public void onEnterState() {
            System.out.printf("%s 开始冷静下来了.
    ", mammoth);
        }
    }

    Mammoth类

    本类是状态State的持有者

    /**
     * 猛犸大象
     */
    public class Mammoth {
    
        private State state;
    
        public Mammoth() {
            state = new PeacefulState(this);
        }
    
        public void timePasses() {
            if (state.getClass().equals(PeacefulState.class)) {
                changeStateTo(new AngryState(this));
            } else {
                changeStateTo(new PeacefulState(this));
            }
        }
    
        private void changeStateTo(State newState) {
            this.state = newState;
            this.state.onEnterState();
        }
    
        public void observe() {
            this.state.observe();
        }
    
        @Override
        public String toString() {
            return "猛犸大象";
        }
    }

    Main

    用于模拟场景以及运行代码

    public class Main {
    
        public static void main(String[] args) {
    
            Mammoth mammoth = new Mammoth();
            // 看看大象现在是什么状态
            mammoth.observe();
    
            // 过了一会儿
            mammoth.timePasses();
    
            // 看看大象现在是什么状态
            mammoth.observe();
    
            // 过了一会儿
            mammoth.timePasses();
    
            // 看看大象现在是什么状态
            mammoth.observe();
    
        }
    }
    

     运行结果如下:

  • 相关阅读:
    (紫书,感谢作者)第7章暴力求解法
    明日更新
    明天更新
    UVa11882最大的数(dfs+剪枝)
    UVa12569树上的机器人的规划
    es6中的reduce方法?
    浏览器是如何渲染页面的?
    判断是不是一个数组?
    判断是否是一个数组?
    var与let的区别?
  • 原文地址:https://www.cnblogs.com/noKing/p/9070117.html
Copyright © 2011-2022 走看看