3

Examples on the Internet, like the example here, confused me about the Command pattern In most examples the concrete command directly calls one of receiver's methods. Is this the only responsibility of a concrete command? Where does the actual business logic belong? In the execute() method of concrete command or in some method on the receiver?

Another question is if we want to implement multi threaded command pattern, our thread pool should receive commands from Invoker and run the execute() methods of concrete commands? Is my understanding correct?

Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
Majid Azimi
  • 5,575
  • 13
  • 64
  • 113
  • 3
    The execution of a command must trigger the receiver. Whether you write the business logic directly inside the receiver or delegate it to another class from within the receiver is a choice you have to make. That being said, you have asked two unrelated questions in one question. Your second question should ideally be posted as another question to increase the chances of getting an answer. Also, I also don't understand your second question at all. Can you please elaborate? – Chetan Kinger May 09 '15 at 07:35

2 Answers2

1

Either is possible, and I've implemented Command with concrete commands that contain the implementation of the command in simple applications, but, in typical large applications, commands need to do nothing more than convey the type of command and any arguments. It's up to the receiver to contain or delegate to the implementation of the behavior.

This is because the client has to depend on concrete commands. If the concrete commands in turn require complex dependencies to implement behavior, the client indirectly depends on those complex dependencies too, which makes for an unstable system. Instead, concrete commands should have no complex dependencies, so that clients can depend on them without fear.

[I ignored your second question. Please move it to a new question so we can answer it separately.]

Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
1

Business logic lies in Receiver (most of the logic) and ConcreteCommand (some logic) classes.

Client calls Invoker => Invoker calls ConcreteCommand => ConcreteCommand calls Receiver method, which implements abstract Command method.

Advantage : Client is not impacted changes in Command and Receiver. Invoker provide loose coupling between Client and Receiver. You can run multiple commands with same Invoker.

Your understanding is correct on thread front. You can treat ExecutorService as Invoker and Runnable or Callable as abstract commands and Implementation classes of Runnable or Callable as Concrete commands/Receivers. I see ConcreteCommand itself plays the role of Receiver in simple multi-threading applications.

Have a look at this question for better understanding :

Using Command Design pattern

Community
  • 1
  • 1
Ravindra babu
  • 37,698
  • 11
  • 250
  • 211