Raz*_*zer 5 .net c# design-patterns state-machine winforms
我写了一个简单的动态FSM.Dynamic
表示状态转换是动态的而不是静态的,如图所示ConcreteStateB
.
namespace FSM_Example
{
using System;
class Program
{
static void Main()
{
var context = new Context(new ConcreteStateA());
context.Run();
Console.Read();
}
}
abstract class State
{
public abstract void Execute(Context context);
}
class ConcreteStateA : State
{
public override void Execute(Context context)
{
context.State = new ConcreteStateB();
}
}
class ConcreteStateB : State
{
public override void Execute(Context context)
{
Console.Write("Input state: ");
string input = Console.ReadLine();
context.State = input == "e" ? null : new ConcreteStateA();
}
}
class Context
{
private State _state;
public Context(State state)
{
State = state;
}
public State State
{
get { return _state; }
set
{
_state = value;
Console.WriteLine("State: " + _state.GetType().Name);
}
}
public void Run()
{
while (_state != null)
{
_state.Execute(this);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这实现了如上所述的状态机GoF305
.
因为我是C#和.net的新手:是否有更好的方法可以使用.net
或更具体的功能来实现这一目标C#
?
Outcoldman的答案提供了许多很棒的选择.
现在,我知道根据模式,下面的代码不是一个合适的FSM,但对于非常简单的实现,它可以帮助您避免编写大量额外的子类.这只是决定工作的正确工具的问题.这个主要关注Action<T>
泛型委托的使用:
public class Context
{
public Action<Context> State { get; internal set; }
public Context(Action<Context> state)
{
State = state;
}
public void Run()
{
while (State != null)
{
State(this);
}
}
}
Run Code Online (Sandbox Code Playgroud)
并将"状态机"视为:
public static class SimpleStateMachine
{
public static void StateA(Context context)
{
context.State = StateB;
}
public static void StateB(Context context)
{
Console.Write("Input state: ");
var input = Console.ReadLine();
context.State = input == "e" ? (Action<Context>)null : StateA;
}
}
Run Code Online (Sandbox Code Playgroud)
为了开始您使用的过程:
var context = new Context(SimpleStateMachine.StateA);
context.Run();
Console.Read();
Run Code Online (Sandbox Code Playgroud)
此外,对于不相关的状态,您也可以使用Lambda表达式,例如:
Action<Context> process = context =>
{
//do something
context.State = nextContext =>
{
//something else
nextContext.State = null;
};
};
Run Code Online (Sandbox Code Playgroud)