Moe's Tech Blog

[Design Pattern] Command Pattern 본문

Software Design Pattern/Notes

[Design Pattern] Command Pattern

moe12825 2022. 8. 27. 06:00

Motivation

  • Think of how a boss in a company uses memos to carry out tasks
    • If the boss needed a worker to schedule a meeting, and also needed another worker to talk to an important client about business, the boss can use memos
    • The boss is a very busy person and may not have time to remember which workers do what jobs and wont have time to walk to the different workers to ask them to complete the tasks
    • Instead, the boss could just write the the tasks down onto a sticky note and a secretary could give these to the workers that can complete them
    • The boss is encapsulating his commands into memos, and likewise, the way requests could be encapsulated into cmmand object in software

 

Command Pattern

  • is a behavioural pattern for encapsulating requests as objects of its own.
  • creates a command object between the sender and receiver
    • This way, the sender does not need to know about the receiver, and the methods to call

  • but what makes the command object do what it's supposed to do, and invoke the specific receiver object to complete the task?
    • this is done by an invoker
      • Invoker makes the command object do what it's supposed to do and get the specific receiver object to complete the task
      • is like secretary at work that executes boss's memo at the right time
    • command manager can also be used
      • command manager keeps track of the commands, manipulates them and invokes them

 

Use Cases

    • 1. Store and schedule different requests
      • when an object calls a method of another object, you can't really do anything to the method calls
        • turning the different requests in your software into command objects can allow you to treat them as the way you would treat other objects
      • If reuqests are turned into command objects in a software, then they can be
        • a. stored into lists
        • b. manipulated before they are completed
        • b. placed onto a queue so that different commands can be scheduled to be completed at different time
          • Example
            • 1. Alarm Ring in calendar software
              • When an event is created in the calendar,
                • A command object could be created to ring the alarm
                • A command object could be placed into a queue so that it is completed when the event is actually scheduled to occur (like run on october 20th. 2022)
    • 2. Allow commands to be undone or redone
      • This is similar to how you can undo or redo edits in a document
      • Example
        • 1. Text editing software
          • There can be many different commands that can be executed like
            • a. delete text
            • b, change font
            • c. pixel text
            • and so on
          • to achieve undo and redo, the software needs two lists:
            • 1. A history list which holds all the commands that have been executed
            • 2. A redo list which would be used to put commands that have been undone
          • every time a command is requested, a command object is created and executed
          • every time a command is completed, that command goes to the history list
          • Now, what if the user wanted to undo a command?
            • The software would look at the history list and look at the most recent command executed
            • The software would ask this command to undo itself and then put it on the redo list
    • 3. Allows command to be stored in a log list
      • if a software suffers from an unexpected crash,

 

Command Pattern UML Diagram

  • Here, Command is super-class
    • defines the common behaviors of your commands
    • each command will have the methods execute, unexecute and isReversable
  • Concrete Commands are instance of sub-classes of this command super-class

Implementing Command Pattern

 

 

 

  • You can see thatPasteCommand extends the Command super-class
  • The PasteCommand object also keeps track of where the text will be inserted and what will be inserted
// Concrete Command
public class PasteCommand extends Command {
    private Document document; // a receiver
    private int position;
    private String text;

    public PasteCommand (Document document, int position, String text) {
        this.document = document;
        this.position = position;
        this.text = text;
    }

    public void execute() {
        document.insertText(this.position, this.text);
    }

    public void unexecute() {
        document.deleteText(this.position, this.text.length());
    }

    public boolean isReversable() {
        return true;
    }
}

 

Benefits of Command Pattern

  • 1. Allows commands to be manipulated as objects
  • 2. Decouples the object of your software program
    • The command object deals with the work by invoking receiver objects
    • Original objects does not need to know what other objects are invovled in the request
  • 3. Allows logic to be pulled from user interfaces
    • command pattern creates a layer where command objects go, so that everytime a button is clicked on the interface, a command object is created
    • The command objects are independent of the user interface so that adding changes like new buttons to the interface is easier and faster
  • 4. Each and every service in a system can be object of its own, allowing more flexibility and functionality
    • command pattern is a great asset to making versatile and easy-to-maintain software system

 

Summary