Question

In the command pattern:

Why shouldn't the client participant be the same class as the invoker participant? Is there possible scenarios when the client participant and the invoker participant can be the same class?

Was it helpful?

Solution

Biggest reason is that it violates the single responsiblity principle. The Client participant and Invoker particpant both have individual responsibilties and a change to one will affect the other.

OTHER TIPS

1) Main responsibility for Client is to proper instanciation of Invoker, Receiver and Command objects and then initiate execution procedure in appropriate place and time.

It could, for example, be something like this

class Client {

...

invoker.executeCommand()

...

}

2) Main responsibility for Invoker is to invoke one or more command-methods of Command Object in particular order.

For example,

class Invoker {

...
command.command1();
command.command2();
command.command3();
...

}

Let's consider, for example, java.awt.event.KeyListener class. It has three methods that is invoked in the following order:

keyPressed(KeyEvent e)
keyTyped(KeyEvent e)
keyReleased(KeyEvent e)

Invoker class for this listener could be:

class KeyInvocation {
    KeyListener listener;

    void invokeKey(EventObject e) {
        listener.keyPressed(e);
        listener.keyTyped(e);
        listener.keyReleased(e);
    }
}

Meantime Client class should proper instanciate EventObject, KeyListener and KeyInvocation and then execute in proper place and time invokeKey method.

Of course Invoker is a additional layer of Command pattern. In simpler case of Command pattern we can skip Invoker class at all and do all the work in Client one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top