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

    状态模式:允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它的类。

    Allow an object to alter its behavior when its internal state changes.The object will appear to change its class

    类结构


    环境类(Context):  定义客户感兴趣的接口。维护一个ConcreteState子类的实例,这个实例定义当前状态。
    抽象状态类(State):  定义一个接口以封装与Context的一个特定状态相关的行为。
    具体状态类(ConcreteState):  每一子类实现一个与Context的一个状态相关的行为。

    代码:

        /// <summary>
        /// 维护了当前状态的主体
        /// </summary>
        public class StateContext
        {
            public StateContext() { }
            public StateContext(State state)
            {
                this.currentState = state;
            }
            private State currentState;
            public State CurrentState
            {
                set
                {
                    currentState = value;
                }
            }
    
            /// <summary>
            /// 执行当前状态
            /// </summary>
            public void Request()
            {
                currentState.Handle(this);
            }
        }
        public interface State
        {
            void Handle(StateContext stateContext);
        }
        /// <summary>
        /// 执行该状态对应的行为,设置下一个状态实例
        /// </summary>
        public class ConcereteStateA : State
        {
            public void Handle(StateContext stateContext)
            {
                Console.WriteLine("状态A:处理行为执行了.....切换下一个状态B......");
                stateContext.CurrentState = new ConcereteStateB();
            }
        }
    
        /// <summary>
        /// 执行该状态对应的行为,设置下一个状态实例
        /// </summary>
        public class ConcereteStateB : State
        {
            public void Handle(StateContext stateContext)
            {
                Console.WriteLine("状态B:处理行为执行了.....切换下一个状态A......");
                stateContext.CurrentState = new ConcereteStateA();
            }
        }

    调用:

                StateContext stateContext = new StateContext(new ConcereteStateA());
                stateContext.Request();
                stateContext.Request();

    结果:


  • 相关阅读:
    localtime函数
    crontab命令加载和使用
    CentOS安装并查看lm_sensors CPU温度监控
    linux查看cpu核数和内存指令
    Unable to start debugging. Unexpected GDB output from command "-environment -cd xxx" No such file or
    EXCEL总结学习
    1.战前准备-字符的输入与输出
    10枚举,结构,联合
    C语言学习目录
    CAD的基础1
  • 原文地址:https://www.cnblogs.com/nygfcn1234/p/3410570.html
Copyright © 2011-2022 走看看