State pattern using methods

你说的曾经没有我的故事 提交于 2019-12-23 18:32:53

问题


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;
}

But I don't know how to write this Func. Is there a way to do this?


回答1:


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.




回答2:


You might want to take a look at this article, which discusses the use of the yield statement for doing state machines. This is commonly done in, for example, in the Unity3d game engine. (another discussion here)




回答3:


if you want to use methods as states and kind of refer to them "generically", you want function pointers. I'm not familiar with the syntax in c# but in c++ you can pass a pointer to a function, and call that function using its pointer. Essentally this means using a function as a paramater/variable - an action that will be used, but is unknown before runtime.

Look into function pointers, I think that will get you where you need to be, although I'm curious about the nature of what you are doing here exactly.

if you ARE using c#, it uses something called function delegates rather than pointers. read here: http://msdn.microsoft.com/en-us/library/ms173171.aspx



来源:https://stackoverflow.com/questions/15607074/state-pattern-using-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!