Search code examples
javadesign-patternscommand-pattern

Role of Invoker class in Command pattern


let's assume that we have command pattern implemented in this way

I am a bit confused about the role of Invoker here. From my point of view:

  1. If we do need history (or any kind of action before command execution), then there is a sense in making this class. But then it breaks Single responsibility principle, yeah? Now it's not only a delegate, it also stores history there.
  2. If we don't need history, I don't see a goal of creating this invoker, that simply performs delegating. Is the only reason for it is just a assumption, that we would need some kind of logic before/after command execution in the future?

Or am I missing something?


Solution

  • If we do need history (or any kind of action before command execution), then there is a sense in making this class. But then it breaks Single responsibility principle, yeah? Now it's not only a delegate, it also stores history there.

    I fully agree with Andreas answer. If you think that you are executing multiple responsibilities, break them into different methods.

    Single Responsibility principle is good to hear but we should not give too much of attention to that principle. If you strictly follow that principle, I am sure that code base is cluttered with too many small classes. I don't think any of big projects in software industry use that principle. The best thing we can do have different methods in same class for different actions.

    If we don't need history, I don't see a goal of creating this invoker, that simply performs delegating. Is the only reason for it is just a assumption, that we would need some kind of logic before/after command execution in the future?

    The core USP of Command pattern is Invoker. It decouples Client ( Sender) and Receiver.

    From oodesign article:

    The Client asks for a command to be executed. The Invoker takes the command, encapsulates it and places it in a queue, in case there is something else to do first, and the ConcreteCommand that is in charge of the requested command, sending its result to the Receiver.

    I have explained the role of Invoker in below SE question:

    Command Pattern seems needlessly complex (what am I failing to understand?)