Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
让一个对象在其内部状态改变的时候,其行为也随之改变。状态模式需要对每一个系统可能取得的状态创立一个状态类的子类。当系统的状态变化时,系统便改变所选的子类。
public interface IState {
void WriteName(StateContext stateContext, string name);
}
public class StateA : IState {
public void WriteName(StateContext stateContext, string name) {
Console.WriteLine(name.ToLower());
stateContext.SetState(new StateB());
}
}
public class StateB : IState {
private int _count;
public void WriteName(StateContext stateContext, string name) {
Console.WriteLine(name.ToUpper());
if (++this._count > 1) {
stateContext.SetState(new StateA());
}
}
}
public class StateContext {
private IState _state;
public StateContext() {
this._state = new StateA();
}
public void SetState(IState state) {
this._state = state;
}
public void WriteName(string name) {
this._state.WriteName(this, name);
}
}
class Client {
static void Main(string[] args) {
var sc = new StateContext();
sc.WriteName("Monday");
sc.WriteName("Tuesday");
sc.WriteName("Wednesday");
sc.WriteName("Thursday");
sc.WriteName("Saturday");
sc.WriteName("Sunday");
Console.ReadKey();
}
}