سؤال

Is there an object-oriented GUI design that would be a reasonable combination of the Command and Observer patterns?

My Java GUI attempts to combine Command and Observer patterns as follows:

  • the client is an observer of the Command receiver (e.g. an input GUI screen, or a dialog)
  • the invoker is an instance variable of the client
  • the update() method of the client receives the Command receiver's input and updates the invoker with the appropriate Command

What is making me uncomfortable with this implementation is that the update() method comprises a huge number of conditional if statements.

e.g.

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

The proper way of using the Command pattern to effectively and efficiently handle GUI events is eluding me at the moment. Is the Observer pattern a useful partner for it?

هل كانت مفيدة؟

المحلول

Well, the overall design solution for UI would be MVC, or some of it's variations (actually, people usually leave out an explicit controller, and have a model and a view which is basically coupled with controller). Commands are not essential there, unless you want to establish an undo framework.

In any case, if you use Java, you are likely to be stuck with a UI library (like Swing or SWT), and this library will impose a great deal of your design.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top