状态模式(State Pattern)
状态模式(State Pattern)是一种行为型模式,又叫做快照模式。当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。状态模式主要解决的是当控制一个对象状态的条件表达式过于复杂时的情况。把状态的判断逻辑转移到表示不同状态的一系列类中,可以把复杂的判断逻辑简化。状态模式在工作流或游戏等各种系统中大量使用。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication
{
//一般每个接口或类都写在单独的.cs文件中
//本示例为了执行查看方便才写在一起
/// <summary>
/// State(抽象状态类)
/// </summary>
public abstract class State
{
public abstract void Handle(Context context);
}
/// <summary>
/// 上下文Context(环境类)
/// </summary>
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: " + _state.GetType().Name);
}
}
public void Request()
{
_state.Handle(this);
}
}
/// <summary>
/// ConcreteState(具体状态类)
/// </summary>
public class ConcreteStatePending : State
{
public override void Handle(Context context)
{
context.State = new ConcreteStateRunning();
}
}
/// <summary>
/// ConcreteState(具体状态类)
/// </summary>
public class ConcreteStateFinished : State
{
public override void Handle(Context context)
{
context.State = new ConcreteStateRunning();
}
}
/// <summary>
/// ConcreteState(具体状态类)
/// </summary>
public class ConcreteStateRunning : State
{
public override void Handle(Context context)
{
context.State = new ConcreteStateFinished();
}
}
class Program
{
static void Main(string[] args)
{
// 上文操作状态
Context c = new Context(new ConcreteStatePending());
// 发出请求,切换状态
c.Request();
c.Request();
c.Request();
c.Request();
}
}
}