zoukankan      html  css  js  c++  java
  • 第十六章 状态模式

    好处:将与特定状态相关的行为局部化,并将不同状态的行为分割开来。

    当一个对象的行为取决于它的状态,并且它必须在运行时刻根据状态改变它的行为时,就可以考虑使用状态模式。

    /**
     * Created by hero on 16-4-4.
     */
    public abstract class State {
        public abstract void handle(Context context);
    }
    /**
     * Created by hero on 16-4-4.
     */
    public class ConcreteStateA extends State {
        @Override
        public void handle(Context context) {
            System.out.println("state a");
            context.setState(new ConcreteStateB());
            context.request();
        }
    }
    /**
     * Created by hero on 16-4-4.
     */
    public class ConcreteStateB extends State {
        @Override
        public void handle(Context context) {
            System.out.println("state b--->the end state");
            //context.setState(new ConcreteStateA());
        }
    }
    /**
     * Created by hero on 16-4-4.
     */
    public class Context {
        private State state;
    
        public void request() {
            state.handle(this);
        }
    
        public Context(State state) {
            this.state = state;
        }
    
        public State getState() {
            return state;
        }
    
        public void setState(State state) {
            this.state = state;
        }
    }
    public class Main {
        public static void main(String[] args) {
            Context context = new Context(new ConcreteStateA());
            context.request();
        }
    }
  • 相关阅读:
    On the fly test
    Spec Explorer 工具学习
    C# Static修饰符的作用
    [转]C#静态方法与非静态方法的比较
    如何获取网站服务器运行状态
    C#快速整理代码格式
    UI auto程序结构组织方式
    TestClass必须是public的
    VS2012如何显示行号
    Error: member names cannot be the same as their enclosing type
  • 原文地址:https://www.cnblogs.com/littlehoom/p/5353122.html
Copyright © 2011-2022 走看看