zoukankan      html  css  js  c++  java
  • 状态模式

      定义:(源于Design Pattern):当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。

    public interface State {
        public void doJob(Washing washing);
    }
    public class Start implements State {
        @Override
        public void doJob(Washing washing) {
            System.out.println("Start Washing Clothes!");
            washing.setState(new Work());
            washing.request();
        }
    }
    public class Work implements State{
        @Override
        public void doJob(Washing washing) {
            System.out.println("Working Now!");
            washing.setState(new End());
            washing.request();
        }
    }
    public class End implements State{
        @Override
        public void doJob(Washing washing) {
            System.out.println("All Finished!");
            washing.setState(null);
        }
    }
    public class Washing {
        private State state = null;
        
        public void setState(State state) {
            this.state = state;
            if (state == null) {
                System.out.println("Current state: null!");
            }
            else {
                System.out.println("Current state: " + state.getClass().getName());
            }
        }
        
        public void request() {
            if (state != null) {
                state.doJob(this);
            }
        }
    }
    public class Demo {
        public static void main(String[] args) {
            Washing washing = new Washing();
            washing.setState(new Start());
            washing.request();
        }
    }
    Current state: state.Start
    Start Washing Clothes!
    Current state: state.Work
    Working Now!
    Current state: state.End
    All Finished!
    Current state: null!
  • 相关阅读:
    exploded archive 和packaged archive 区别
    MyEclipse6.5使用设置技巧及快捷键
    本机上设置域名解析
    Cookie的生命周期问题
    简单的函数柯里化
    cookie操作
    自定义事件
    解耦应用逻辑/事件处理程序
    dragdrop + 自定义事件
    在窃取函数中用作用域安全的构造函数
  • 原文地址:https://www.cnblogs.com/lzh66/p/13285399.html
Copyright © 2011-2022 走看看