lundi 14 novembre 2022

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

Aucun commentaire:

Enregistrer un commentaire