Command - rFronteddu/general_wiki GitHub Wiki

The Command pattern is a behavioral design pattern in object-oriented programming that encapsulates a request as an object, thereby decoupling the sender of a request from the object that performs the actual operation. This allows for requests to be treated as objects, offering several benefits.

Key Components:

  • Command: An interface/abstract class declaring an execute() to perform the specific action.
  • Concrete Command: Implements the Command interface and binds a receiver object with an action. It contains all the necessary information to act, including the receiver and any required parameters.
  • Receiver: The object that knows how to perform the actual work. The ConcreteCommand delegates the execution to the Receiver.
  • Invoker: Holds a Command object and, at the appropriate time, asks the command to carry out its request by calling its execute() method. The Invoker does not know the concrete class of the command or the receiver.
  • Client: Creates the ConcreteCommand object, sets its Receiver, and associates it with an Invoker.

Benefits:

  • Decoupling: Separates the object that invokes an operation from the object that knows how to perform it.
  • Parameterization: Allows clients to be parameterized with different requests, operations, or algorithms.
  • Queueing and Logging: Commands can be queued, logged, and their execution can be scheduled.
  • Undo/Redo Functionality: By storing a history of executed commands, it becomes possible to implement undo and redo operations.
  • Macro Commands: Multiple commands can be grouped into a single composite command.

Example Analogy:

Consider a restaurant order system. The Client (customer) places an order. The Invoker (waiter) takes the order (a ConcreteCommand like "OrderBurgerCommand") and gives it to the Receiver (cook), who knows how to prepare the meal. The waiter doesn't need to know how to cook; they just know how to pass the order.