是否存在一种将命令模式和观察者模式合理组合的面向对象的 GUI 设计?
我的 Java GUI 尝试组合命令模式和观察者模式,如下所示:
- 客户端是命令接收器的观察者(例如输入 GUI 屏幕或对话框)
- 调用者是客户端的实例变量
- 客户端的 update() 方法接收命令接收者的输入并使用适当的命令更新调用者
让我对这种实现感到不舒服的是 update() 方法包含大量条件 if 语句。
例如
public class Client implements Observer {
InputScreen inputScreen;
Invoker director;
InputScreenCommand inputScreenCommand;
public Client {
inputScreen = new InputScreen();
inputScreen.registerObserver(this);
inputScreenCommand = new InputScreenCommand(inputScreen)
director.setCommand(inputScreenCommand);
director.invoke();
}
public void update(String command) {
if (command.equals("Input Screen 2")) {
inputScreen.removeObserver(this);
// generate new receiver/subject
inputScreen2.registerObserver(this);
// generate new Command
director.setCommand(inputScreen2Command);
director.invoke();
}
// and so on through all the permutations of input from receivers
}
}
使用命令模式来有效和高效地处理 GUI 事件的正确方法目前正在躲避我。观察者模式对它有用吗?