Introduction to the Command Pattern

Introduction to the Command Pattern

Welcome to the Behavioral Patterns course! In this lesson, we will explore the Command Pattern, a fundamental design pattern that is highly useful for promoting flexible and reusable code. This pattern is particularly effective in scenarios where you need to parameterize objects with operations, queues, or logs.

You might remember from previous lessons that behavioral design patterns help with object communication and responsibility distribution within your software. The Command Pattern encapsulates a request as an object, thereby allowing users to parameterize clients with queues, requests, and operations. This encapsulation enables us to decouple the sender from the receiver, enhancing the flexibility and maintainability of the system.

The Command Pattern involves creating a command interface with an execute method. We then create concrete command classes that implement this interface, each representing a specific action. Finally, we'll integrate these commands with a request invoker to execute the actions. This structure allows us to easily extend or modify commands without changing the invoker or the receiver.

Key Components and Their Implementation

To understand the Command Pattern, we should first identify its essential components: Command, Receiver, Concrete Commands, and Invoker. Here's a breakdown of each component, along with their implementations. Each of these components plays a critical role in decoupling the sender and receiver, thereby making the system more modular and flexible.

Command Interface

The Command interface declares an execute method that must be implemented by all concrete commands. This interface will help us define the actions to be executed. This interface enables a consistent method signature for executing various commands, making the system easier to extend.

Python
from abc import ABC, abstractmethod

class Command(ABC):
    @abstractmethod
    def execute(self):
        pass

Receiver

The receiver is the object that performs the actual action. In our example, the Light class will serve as the receiver that can turn the light on or off. The receiver contains the actual logic that gets executed when the command is invoked.

class Light:
    def on(self):
        print("Light is on.")

    def off(self):
        print("Light is off.")
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal