何时使用状态模式?

时间:2011-11-15 22:22:42

标签: actionscript-3

我正在开发一个Flash项目,该项目最初有一个简单的动画模板,但已经增长到具有多个模板的不同“状态”(不在我的控制之下)

因此,我的更新(ENTER_FRAME)循环现在看起来有点像这样:

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;
}

}

我的初始化方法开始如下:

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;
            }
    }

我为伪代码道歉,但真正的代码非常冗长。

这是一种使用状态模式会更好的情况吗?如果是这样的话,任何人都可以提供一个(短)代码示例来说明如何最好地实现它?

1 个答案:

答案 0 :(得分:1)

你敢打赌这是一个使用状态模式的绝佳机会!每当我不得不开始嵌套switch语句时,我就会使用它,最值得注意的是"ActionScript 3.0 Design Patterns" (O'Reilly)中推荐的实现。

(对不起,我找不到可以自由访问的章节链接,但我认为这本书非常物有所值。)

相关问题