Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

State machine with interface-separated states

In a classic version of states, each state implementing some interface. So we can pass execution to any current state

class Context
{
    private State _state;

    public void MethodA()
    {
        _state.MethodA();
    }

    public void MethodB()
    {
        _state.MethodB();
    }
}

But in my case. I have a gameplay feature. It offers something to buy. And it also has states, like "Active", "Buying", "Preparing", "Finished" and so on. From some of them buying is allowed, from others - not. In more abstract way - each of states implement only part of the context's interface methods. And methods may intersect

class ConcreteStateA
{
    public void MethodA()
    {
        // Do A
    }

    // No MethodB
}

class ConcreteStateB
{
    // No MethodA

    public void MethodB()
    {
        // Do B
    }
}

The question: is it any modification to use state machine this way? The current variation cause to directly check whether it's correct state or not before call in context. State classes hierarchy doesn't save from the problem of state type checking

like image 793
pavdan Avatar asked Jun 23 '26 00:06

pavdan


1 Answers

you can add an interface that has a method named 'Handle'. then you can implement that interface in your concrete class. by this approach you can just say what to do next from this state and you are not forced to implement other states.

see this: https://www.dotnettricks.com/learn/designpatterns/state-design-pattern-c-sharp

like image 188
Hamidreza Aliyari Avatar answered Jun 24 '26 13:06

Hamidreza Aliyari



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!