سؤال

I’m currently building a generic state machine and I’m using the constructor of the StateMachine with a generic parameter to set the fallback state at creation, in the event that there is nothing for the machine to do.

I was wondering if it’s bad practice to have two constructors, one that is used by the state machine itself when needing to create new state objects, and another that is used when initializing the state machine for the first time (setting that default fallback state).

My biggest question: Am I abusing generics, and is there a time when generics shouldn’t be used?

State machine creation:

//The generic parameter is the default "fallback" state.
_nodeStateMachine = new NodeStateMachine<IdleNodeState>();

State machine constructor:

public NodeStateMachine()
{
    _currentState = new T();
}

Here is how states would be changed in the NodeStateMachine class:

public void ChangeState<U>() where U : INodeState, new()
{
    _nextState = new U();
}

The constructors in question lie directly in the states themselves:

public NullNodeState(){} // To use the class generically.

public NullNodeState(ConditionCheck check)
{
    _nullCheck = check;   
}
هل كانت مفيدة؟

المحلول

I don't see how the state machine is generic, since it appears the only restriction is the states implement INodeState. In that case, I would create a static factory method specifying the initial state:

public class NodeStateMachine
{
    private INodeState _nextState;
    private NodeStateMachine(INodeState initial)
    {
        _nextState = initial;
    }

    public void ChangeState<U>() where U : INodeState, new()
    {
        _nextState = new U();
    }

    public static NodeStateMachine Create<T>() where T : INodeState, new()
    {
        return new NodeStateMachine(new T());
    }

    public static NodeStateMachine Create(INodeState initial)
    {
        return new NodeStateMachine(initial);
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top