状态模式是一种对象行为型设计模式,对有若干对象的状态,将每一种状态封装成一个对象,把负载的判读逻辑提取到不同的对象中。以线程的转换为例。如下所示:
namespace Designmode.State
{
/// <summary>
/// 线程状态抽象类
/// </summary>
public abstract class ThreadState
{
/// <summary>
/// 状态名称
/// </summary>
public string Name { get; set; }
}
}
namespace Designmode.State
{
/// <summary>
/// 新建状态
/// </summary>
public class NewState:ThreadState
{
/// <summary>
/// 构造一个新建状态实例
/// </summary>
public NewState()
{
this.Name = "New";
}
/// <summary>
/// 开始运行
/// </summary>
/// <param name="hj">想成上下文</param>
public void Start(ThreadContext hj)
{
hj.SetState(new RunnableState());
Console.WriteLine($"State: {this.Name} to {hj.GetState().Name}");
}
}
}
namespace Designmode.State
{
/// <summary>
/// 可运行状态类
/// </summary>
public class RunnableState:ThreadState
{
/// <summary>
/// 可运行的状态
/// </summary>
public RunnableState()
{
this.Name = "Runable";
}
/// <summary>
/// 获取CPU
/// </summary>
/// <param name="hj">线程上下文</param>
public void GetCPU(ThreadContext hj)
{
hj.SetState(new RunningState());
Console.WriteLine($"State: {this.Name} to {hj.GetState().Name}");
}
}
}
namespace Designmode.State
{
/// <summary>
/// 运行状态类
/// </summary>
public class RunningState:ThreadState
{
/// <summary>
/// 构造一个运行状态类
/// </summary>
public RunningState()
{
this.Name = "Running";
}
/// <summary>
/// 暂停
/// </summary>
/// <param name="hj">线程上下文</param>
public void Suspend(ThreadContext hj)
{
hj.SetState(new BlockedState());
Console.WriteLine($"State: {this.Name} to {hj.GetState().Name}");
}
/// <summary>
/// 停止
/// </summary>
/// <param name="hj">线程上下文</param>
public void Stop(ThreadContext hj)
{
hj.SetState(new DeadState());
Console.WriteLine($"State: {this.Name} to {hj.GetState().Name}");
}
}
}
namespace Designmode.State
{
/// <summary>
/// 线程阻塞状态
/// </summary>
public class BlockedState:ThreadState
{
/// <summary>
/// 构造一个阻塞状态实例
/// </summary>
public BlockedState()
{
this.Name = "Blocked";
}
/// <summary>
/// 恢复
/// </summary>
/// <param name="hj">线程上下文</param>
public void Resume(ThreadContext hj)
{
}
}
}
namespace Designmode.State
{
/// <summary>
/// 线程死亡状态
/// </summary>
public class DeadState:ThreadState
{
/// <summary>
/// 构造一个死亡状态实例
/// </summary>
public DeadState()
{
this.Name = "Dead";
}
/// <summary>
/// 线程死亡
/// </summary>
public void Dead()
{
}
}
}