状态模式:
State:当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。
状态模式主要解决的是当控制一个对象状态转换的条件表达式过于复杂时的情况。
把状态的判定逻辑转移到表示不同状态的一系列类当中,可以把复杂的判断逻辑简化。
Demo:
//维护一个ConcreteState子类的实例,定义当前的状态
class Context
{
private State state;
public Context(State state)//定义Context的初始状态
{
this.state = state;
}
public State State//读写当前状态和设置新状态
{
get { return state; }
set
{
state = value;
Console.WriteLine("当前状态:"+state.GetType().Name);
}
}
//对请求做处理,并设置一下状态
public void Request()
{
state.Handle(this);
}
}
abstract class State
{
public abstract void Handle(Context context);
}
classConcreteStateA : State
{
public override void Handle(Context context)
{
context.State = newConcreteStateB();//设置下一状态
}
}
class ConcreteStateB : State
{
public override void Handle(Context context)
{
context.State = new ConcreteStateA();//设置下一状态
}
}
classProgram
{
static void Main(string[] args)
{
Context c = new Context(new ConcreteStateA());
c.Request();
c.Request();
c.Request();
c.Request();
Console.ReadKey();
}
}
Demo2:
public class Work
{
private State current;
public Work()
{
current = new ForenoonState();
}
private double hour;
public double Hour
{
get { return hour; }
set { hour = value; }
}
private bool finish = false;
public bool TaskFinished
{
get { return finish; }
set { finish = value; }
}
public void SetState(State s)
{
current = s;
}
public void WriteProgram()
{
current.WriteProgram(this);
}
}
public abstract class State
{
public abstract void WriteProgram(Work w);
}
public class ForenoonState : State//上午工作状态
{
public override void WriteProgram(Work w)
{
if (w.Hour < 12)
{
Console.WriteLine("当前时间:{0}点 上午工作,精神百倍", w.Hour);
}
else
{
w.SetState(new NoonState());
w.WriteProgram();
}
}
}
Work w = new Work();
w.Hour=1;
w.WriteProgram();
w.Hour=2;
w.WriteProgram();