状态模式:当一个对象的内在状态改变时,允许改变其行为。这个对象看起来像是改变了其类。主要解决是当控制一个对象状态装换的条件表达式过于复杂时的情况,把状态的判断逻辑转移到表示不同的状态的一系列类中。可以把复杂的逻辑简化。
状态模式的结构图:
先定义一个抽象状态类:
abstract class State
{
public abstract void Handle(Context context);
}
{
public abstract void Handle(Context context);
}
ConcreteStateA、 ConcreteStateB:继承State
class ConcreteStateA : State
{public override void Handle(Context context)
{
//throw new NotImplementedException();
context.State = new ConcreteStateB();
}
}
class ConcreteStateB : State
{
public override void Handle(Context context)
{
//throw new NotImplementedException();
context.State = new ConcreteStateA();
}
}
{
public override void Handle(Context context)
{
//throw new NotImplementedException();
context.State = new ConcreteStateA();
}
}
互相实例化对方。
还要定义一个内容类:
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);
}
}
{
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);
}
}
在主函数中调用:
class Program
{
static void Main(string[] args)
{
Context c = new Context(new ConcreteStateA());
c.Request();
c.Request();
c.Request();
c.Request();
Console.ReadKey();
}
}
{
static void Main(string[] args)
{
Context c = new Context(new ConcreteStateA());
c.Request();
c.Request();
c.Request();
c.Request();
Console.ReadKey();
}
}