Reputation: 136
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?
Upvotes: 1
Views: 1947
Reputation: 11
So let's take an example of a text editor. When you open an application the application is the client and it will store various receivers and command in their invokers. eg. It will add pasteCommand to paste menu item where receiver is the document. It will add openCommand to open menu item where receiver is the application itself.
This exactly answers your question how invoker and client can be different
Upvotes: 0
Reputation: 875
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.
Upvotes: 0
Reputation: 2030
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.
Upvotes: 6