状态模式(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));
            }
        }
    }

}
posted @ 2017-01-09 16:04  盘子脸  阅读(491)  评论(0编辑  收藏  举报