1

这是一个关于将输入键映射到实现状态模式的类中的动作的最佳策略的编程风格问题。

我正在处理两个类:

第一个实现状态模式,它控制多状态物理设备:

class DeviceController {
    State _a, _b, _current;

    // Actions that may prompt a transition from one state to another
    public void actionA() { ... }
    public void actionB() { ... }
    public void actionC() { ... }

    public State getStateA() { ... }
    public State getStateB() { ... }

    public void setCurrentState() { ... }
};

第二个是 KeyListener,它检索所有键盘输入并在按下的输入键与(暂时)硬编码绑定表匹配时从设备控制器调用适当的操作:

class KeyDemo implements KeyListener {

    DeviceController _controller;
    ...
    @Override
    public void keyPressed(KeyEvent arg0) {
        char key = Character.toUpperCase(arg0.getKeyChar());
        switch (key) {
        case 'A':
            _controller.actionA();
            break;
        case 'B' :
        ...
    }
    ...
}

是否有最佳实践编码风格将键绑定到控制器中的操作?我是否必须像示例代码中那样通过 switch 语句?在我看来,这个解决方案有点脏代码:状态模式不是应该消除不可维护的 if 和 switch 控制结构吗?

谢谢你的建议。

4

1 回答 1

0

使用多态性可以实现您的目标。我使用过枚举,但也许更适合使用接口或抽象类,然后实现每个关键处理器。你怎么看?

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

enum KeyProcessor {
    A {
        void executeAction() {
            _controller.actionA();
        }
    },
    B {
        void executeAction() {
            _controller.actionB();
        }
    };

    private static final DeviceController _controller = new DeviceController();

    void executeAction() {
        System.out.println("no action defined");
    }
}

class DeviceController {
    State _a;
    State _b;
    State _current;

    // Actions that may prompt a transition from one state to another
    public void actionA() {
        System.out.println("action A performed.");

    }

    public void actionB() {
        System.out.println("action B performed.");
    }

    public void actionC() {
    }

    public State getStateA() {
        return null;
    }

    public State getStateB() {
        return null;
    }

    public void setCurrentState() {
    }
} // end class DeviceController

public class KeyDemo implements KeyListener {

    DeviceController _controller;

    // ...
    @Override
    public void keyPressed(KeyEvent arg0) {
        keyPressed(Character.toUpperCase(arg0.getKeyChar()));
        // ...
    }

    public void keyPressed(char c) {
        KeyProcessor processor = KeyProcessor.valueOf(c + "");
        if (processor != null) {
        processor.executeAction();
    }

    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }

    public static final void main(String[] args) {
        KeyDemo main = new KeyDemo();
        main.keyPressed('A');
        main.keyPressed('B');
    }
} // end class KeyDemo

class State {
}
于 2012-05-18T10:43:22.923 回答