状态模式的使用方法 [英] State pattern using methods
问题描述
我正在尝试基于状态模式的修改版本来实现一个简单的状态机,该状态机将方法用作状态而不是类,就像这样:
I'm trying to implement a simple state machine based on a modified version of the state pattern using methods as states instead of classes, something like this:
private Action<Input> currentState;
private void NextState(Input i) {
currentState(i);
}
private void State1(Input i) {
if( i ... )
currentState = State1;
else
currentState = State2;
}
private void State2(Input i) {
if( i ... )
currentState = State1;
else
currentState = State2;
}
但是如果可以的话,它会更加优雅:
But it would be more elegant if I could do:
private void NextState(Input i) {
currentState = currentState(i);
}
private Func<xxx> State1() {
if( i ... )
return State1;
else
return State2;
}
但是我不知道怎么写这个Func
.有办法吗?
But I don't know how to write this Func
. Is there a way to do this?
推荐答案
如果要使用返回void
的函数,请尝试使用 Action
.
If you want to use functions which return void
, try using Action
instead.
private Action State1() {
if( ... )
return State1Inner;
else
return State2Inner;
}
如果要使用返回带有其自身签名的函数的函数,则必须首先定义一个自定义委托类型.这是通用版本:
If you want to use a function which returns a function with it's own signature, you have to define a custom delegate type first. Here's a generic version:
public delegate State<T> State<T>(T input);
private State<int> State1(int input) {
if( ... )
return State1;
else
return State2;
}
这将帮助您避免具有内部状态功能.
This will help you avoid having inner state functions.
这篇关于状态模式的使用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!