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

    让一个对象随着内部的状态改变而发生改变.

    状态的两种切换方式:

    1) 完全交给Context类切换,

    2) 给Context初始化状态,其他的切换根据每一个State类进行切换,Context对象不再介入

    namespace ConsoleApplication21
    {
        class Program
        {
            static void Main(string[] args)
            {
                Context c = new Context();
                c.SetState(new A(c));
                c.Request("吃屎");
                c.Request("C");
                c.Request("B");
                c.Request("我在吃屎");
                Console.ReadLine();
            }
        }
    
    
        public class Context
        {
            private State mState;
    
            public void SetState(State state)
            {
                mState = state;
            }
    
            public void Request(string value)
            {
                mState.Handle(value);
            }
        }
    
        public class State
        {
            protected Context mContext;
    
            public State(Context c)
            {
                mContext = c;
            }
    
            public virtual void Handle(string value)
            {
                Console.WriteLine(value);
            }
        }
    
        public class A : State
        {
            private Context c;
    
            public A(Context c) : base(c) { }
    
            public override void Handle(string value)
            {
                Console.WriteLine("A " + value);
    
                if (value == "C")
                {
                    mContext.SetState(new C(mContext));
                }
            }
        }
        public class B : State
        {
            public B(Context c) : base(c) { }
            public override void Handle(string value)
            {
                Console.WriteLine("B " + value);
                if (value == "A")
                {
                    mContext.SetState(new A(mContext));
                }
            }
        }
        public class C : State
        {
            public C(Context c) : base(c) { }
            public override void Handle(string value)
            {
                Console.WriteLine("C " + value);
                if (value == "B")
                {
                    mContext.SetState(new B(mContext));
                }
            }
        }
    
    }
  • 相关阅读:
    WebStorm 使用
    Mac上因磁盘格式导致gulp无限刷新问题
    JS数组随机排序
    Javascript高性能动画与页面渲染
    两列布局,左边固定,右边自适应的三种方法
    google pay app权限使用说明
    javaFX
    https网站引用http路径的js和css失效解决办法
    tomcat笔记
    java sigar.jar
  • 原文地址:https://www.cnblogs.com/plateFace/p/6265592.html
Copyright © 2011-2022 走看看