Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Command Pattern

1. Introduction

The Command Pattern is a behavioral design pattern that turns a request into a stand-alone object. This object contains all the information necessary to perform the action. This decouples the sender of the request from the receiver.

2. Key Concepts

  • Command: An interface that defines a method for executing a command.
  • ConcreteCommand: Implements the Command interface and defines the binding between a receiver and an action.
  • Receiver: The object that performs the actual work when the command is executed.
  • Invoker: Asks the command to execute the request.
  • Client: Creates a ConcreteCommand and sets its receiver.

3. Structure


class Command {
    execute(): void;
}

class ConcreteCommand implements Command {
    private receiver: Receiver;

    constructor(receiver: Receiver) {
        this.receiver = receiver;
    }

    execute(): void {
        this.receiver.action();
    }
}

class Receiver {
    action(): void {
        console.log("Receiver action executed.");
    }
}

class Invoker {
    private command: Command;

    setCommand(command: Command): void {
        this.command = command;
    }

    invoke(): void {
        this.command.execute();
    }
}

class Client {
    static main(): void {
        const receiver = new Receiver();
        const command = new ConcreteCommand(receiver);
        const invoker = new Invoker();

        invoker.setCommand(command);
        invoker.invoke();
    }
}
            

4. Implementation

The implementation of the Command Pattern is straightforward:

  1. Define the Command Interface: Create an interface with a method for executing commands.
  2. Implement Concrete Commands: Create classes that implement the Command interface.
  3. Create the Receiver: Develop the classes that will execute the commands.
  4. Setup the Invoker: Implement an invoker that will call the commands.
  5. Create the Client: Use the concrete commands, receiver, and invoker to execute actions.

5. Best Practices

When using the Command Pattern, consider the following best practices:

  • Use Command Pattern when you need to parameterize objects with operations.
  • Consider using it for queueing requests or logging changes.
  • Keep commands simple and focused on a single action.

6. FAQ

What are the benefits of the Command Pattern?

The Command Pattern offers flexibility in command execution, easy undo/redo functionality, and decouples the sender from the receiver.

When should I use the Command Pattern?

Use the Command Pattern when you need to encapsulate all details of a request as an object, especially when you need to queue operations, log them, or have undo functionality.