赞
踩
当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类
- abstractclass State
- {
- public abstract void Handler(Context context);
- };
-
- class ConcretStateA :State
- {
- public override void Handler(Context context)
- {
- context.State = new ConcretStateB();
- }
- };
-
- class ConcretState :State
- {
- public override void Handler(Context context)
- {
- context.State = new ConcretStateA();
- }
- };
-
- 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.Handler(this); //对请求做处理并设置下一个状态
- }
- };
-
- void main()
- {
- Context c = new Context(new ConcretStateA());
-
- c.Request(); //不断的请求同时更改状态
- c.Request();
- c.Request();
- c.Request();
- }
状态模式主要解决的是当前控制一个对象状态转换
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。