Pregunta

Im designing a game, that transitions through a handful of states, I have seen two patterns being used, one is the following:

1) enum pattern where as such:

static {
    // standard states
    transitions.put(PHASE 1, new State[]{PHASE2, PHASE3, PHASE4});

2) The state pattern in a class, where you have an abstract, and sub classes that extend the abstract and represent each state.. the monostate pattern?

im kinda torn between the two, both look like good solutions, what would be more cleaner for a game and easier to understand?

Personally i like the monostate, but enum method seems to be the way.

¿Fue útil?

Solución

As far as "cleaner code", that is a matter of choice.

Some things to consider

What will happen to the code should you add another state and N transitions? Is it still readable to you and the other developers on the team? Try and come to some sort of consensus or perhaps embody this in a code style guideline.

IMHO, since the language you are using is object oriented, I would use the State pattern from the GOF book since it utilizes encapsulation and polymorphism.

If you were writing it in 'C', I would opt for the table-driven approach.

Otros consejos

That depends on whether you need to store any business logic in the state or not. The second option probably makes this easier. All your states can implement something like:

interface State {
    State transition(Event event);
}

and then you can have a kind of manager class that lets you manage the transition:

class StateManager {
    State actualState = new BaseState();
    void processEvent(Event event) {
        actualState = actualState.transition(event);
    }
}

Your implementations of State then choose and return what the next state should be based upon the input.

You're basically implementing a finite-state machine.

If your machine is liable to become complicated quickly, you should, as @duffymo says, externalise the transitions. I'm sure there are libraries out there that do this, though I don't know of any by name.

I'd recommend neither. Write a finite state machine and externalize the states and transitions into XML or JSON. It'll be a far more flexible design.

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