设计模式:状态模式

状态模式(State):当一个对象的内在状态改变时允许改变其行为,这个对象看起来像时改变了其类。

namespace StateDesign
{
    public abstract class State
    {
        public abstract void Handle(Context context);
    }
    public class ConcreteStateA : State
    {
        public override void Handle(Context context)
        {
            context.State=new ConcreteStateB();
        }
    }
    public class ConcreteStateB : State
    {
        public override void Handle(Context context)
        {
            context.State = new ConcreteStateA();
        }
    }
    public class Context
    {
        private State state;
        public Context(State state)
        {
            this.state = state;
        }
        public State State
        {
            get { return state; }
            set
            {
                state = value;
                Console.WriteLine("当前状态:" + state.GetType().Name);
            }
        }
        public void Request()
        {
            state.Handle(this);
        }
    }
}
View Code

测试代码:

            StateDesign.Context c = new StateDesign.Context(new ConcreteStateA());
            c.Request();
            c.Request();
            c.Request();
            c.Request();
View Code

 

posted @ 2016-03-15 09:24  uptothesky  阅读(131)  评论(0编辑  收藏  举报