Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 879
Roberto Avatar asked Jun 10 '26 21:06

Roberto


2 Answers

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.

like image 136
p.s.w.g Avatar answered Jun 12 '26 10:06

p.s.w.g


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)

like image 34
theodox Avatar answered Jun 12 '26 12:06

theodox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!