gpt4 book ai didi

java - 实现状态模式时将键绑定(bind)应用于状态转换

转载 作者:行者123 更新时间:2023-12-01 05:42:22 25 4
gpt4 key购买 nike

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

我正在处理两个类:

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

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,它检索所有键盘输入,并在按下的输入键与(暂时)硬编码绑定(bind)表匹配时从设备 Controller 调用适当的操作:

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' :
...
}
...
}

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

感谢您的建议。

最佳答案

使用多态性您可以实现您的目标。我已经使用了枚举,但也许使用接口(interface)或抽象类然后实现每个关键处理器会更合适。你觉得怎么样?

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

关于java - 实现状态模式时将键绑定(bind)应用于状态转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6783323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com