Team Template: Client and Invoker

In the command template:

Why doesn't the client member have to be the same class as the member member? Are there possible scenarios where the client principal and caller principal can be of the same class?

+1


a source to share


2 answers


The biggest reason is that it violates the principle of single responsibility. The Client Member and Invoker Member have individual responsibilities and changing one will affect the other.



+4


a source


1) The primary responsibility for the Client is to correctly create the Invoker, Receiver and Command objects and then initiate the execution procedure at the appropriate place and time.

It could be, for example, something like this

class Client {

...

invoker.executeCommand()

...

}

      

2) The primary responsibility for Invoker is to call one or more Command Object methods in a specific order.

For instance,

class Invoker {

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

}

      



Consider, for example, the java.awt.event.KeyListener class. It has three methods, which are called in the following order:

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

      

The Invoker class for this listener could be:

class KeyInvocation {
    KeyListener listener;

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

      

At the same time, the client class must have the proper instationiate EventObject, KeyListener, and KeyInvocation, and then execute the invokeKey method at the correct time and place.

Invoker is of course an additional layer of the Command template. In the simpler case of the Command template, we can skip the Invoker class altogether and do all the work in Client one.

0


a source







All Articles