redconservatory
redconservatory

Reputation: 21934

When to use State pattern?

I am working on a Flash project that initially had a simple template for the animation, but has grown to have different "states" with multiple templates (not under my control)

Because of this, my update (ENTER_FRAME) loop is now starting to look a bit like this:

private function update():void {
  switch (state) {

    case "intro":
        switch(layoutState) {
            case "large-images":
                // do one animation
            break;

            case "thumbnails":
                // do another animation
            break;

            case "text-on-top":
                // do another animation
            break;
        }
    break;

    case "main":
        switch(layoutState) {
            case "large-images":
                // do another animation
            break;

            case "thumbnails":
                // do another animation
            break;

            case "text-on-top":
                // do another animation
            break;
        }

    break;

    case "outro":
        switch(layoutState) {
            case "large-images":

            break;

            case "thumbnails":

            break;

            case "text-on-top":

            break;
        }

    break;
}

switch(backgroundState) {
    case "black":
        // do something
    break;

    case "white":
        // do something else
    break;
}

}

And my initialization methods are starting to look like:

private function initalizeDescription() {
        description = new Description();
        switch(layoutState) {
                case "large-images":
                    // do something to description here
                break;

                case "thumbnails":
                    // do something else to description here 
                    if (backgroundState == "black") {
                        // do one thing
                    } 
                    if (backgroundState == "white") {
                        // do another thing
                    }
                break;

                case "text-on-top":
                    // do something else to description here
                break;
            }
    }

I apologize about the pseudo-code but the real code is quite lengthy.

Is this a situation where it would just be better to use a state pattern, and if so can anyone provide a (short) code sample of how best to implement this?

Upvotes: 0

Views: 388

Answers (1)

weltraumpirat
weltraumpirat

Reputation: 22604

You bet this is a great opportunity to use the state pattern! I use it whenever I would otherwise have to start nesting switch statements, most notably the implementation recommended in "ActionScript 3.0 Design Patterns" (O'Reilly).

(I'm sorry I couldn't find a freely accessible version of the chapter to link to, but I think the book is well worth the money.)

Upvotes: 1

Related Questions