Pregunta

I have implemented a simple state pattern that should run on top of my model classes. My application is written in C# WPF.

First of all, I am not quite sure where I need to put my state pattern logic. Should I put it into my controller or service classes?

Suppose you want to verify a few things before making the actual transition. Currently I have created a specification which can be called directly from the state pattern class.

But is this the right approach?

 interface ISpecification<T>
{
    bool IsSatisfiedBy(T sut);
}

class DetermineDockingSate:ISpecification<Vehicle>
{
    public bool IsSatisfiedBy(Vehicle sut)
    {
        throw new NotImplementedException();
    }
}

This is for verification/checkpoints inside a state pattern. But what about actions that should be performed inside a state pattern before making the transition.

I would implement these actions in a sort of service class and call these service class directly from my state pattern.

 public override void Dock()
    {
        Console.WriteLine("Dock Machine and going to the Vehicle status.");

        DockingStateEngineService myService = new DockingStateEngineService();

        Func<string,bool> messageTarget;

        messageTarget = myService.DetermineDockingSate;

        bool ok = messageTarget("NOT");

        this.Engine.setCurrentState(Engine.Vehicle);
    }

Is this again the correct approach?

¿Fue útil?

Solución

According to HeadFirst, should the concrete states decide what the next state will be is a question with no absolute answer.
If the state transitions are fixed, then it's appropriate for the context to decide the next state.
If the transitions are more dynamic, the decision is usually placed in the state classes (for example, if the decision is dependent of the runtime value of a variable in the context class).

Obviously, this creates dependencies between the state classes. This can be minimized by having the state as members in the context class.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top