Design Patterns - (18) Command Patterns (Swift Version)

One, the concept:

  In a software system, "behavior requester" and "behavior implementer" usually present a "tight coupling". But in some cases, such as "recording, undo/redo, transaction" for behavior, such tight coupling that cannot resist changes is not appropriate. How to decouple the "behavior requester" from the "behavior implementer" in this case? Abstract a set of behaviors as objects to achieve loose coupling between the two. This is the Command Pattern (Command Pattern).

 

2. Class diagram:

  

  

  Command:
    Define the interface of the command and declare the method of execution.
  ConcreteCommand:
    The command interface implementation object is a "virtual" implementation; it usually holds the receiver and calls the receiver's function to complete the operation to be performed by the command.
  Receiver:
    Receiver, the object that actually executes the command. Any class can be a receiver, as long as it can implement the corresponding function that the command requires.
  Invoker:
    The command object is required to execute the request, which usually holds the command object, and can hold many command objects. This is where the client actually triggers the command and asks the command to perform the corresponding action, which is equivalent to using the entry of the command object.
  Client:
    Create a specific command object and set the receiver of the command object. Note that this is not a client in our conventional sense, but is assembling the command object and receiver. Perhaps, it is better to call this Client an assembler, because the client that actually uses the command is triggered from the Invoker.
 
Three, cooperation mode:
  1. Client creates a ConcreteCommand object and specifies his Receiver object
  2. An Invoker object stores the ConcreteCommand object
  3. The Invoker submits a request by calling the Execute operation of the Command object. If the command is undoable, ConcreteCommand stores the current state for canceling the command before executing the Execute operation
  4. The ConcreteCommand object performs some operations on the Receiver that calls it to execute the request
 
Fourth, the code example:

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326661480&siteId=291194637