Course contentsShow
← Python
Lesson 492 of 1,0607. Object-Oriented ProgrammingFree lesson

Decoupling Logic with the Command Pattern

Encapsulate requests as standalone objects to support parameterization, queuing, and undoable operations within your object-oriented system.

In this lesson, you will learn how to decouple your system’s actions from the objects that trigger them by wrapping requests into standalone objects.

The Problem: Tight Coupling

In many object-oriented systems, an object (the "Invoker") often calls methods directly on another object (the "Receiver"). This creates tight coupling: the Invoker must know exactly which method to call and what arguments to provide. If you want to queue these actions, log them, or implement an "Undo" feature, your code becomes cluttered with conditional logic.

The Command Pattern Solution

The Command Pattern addresses this by encapsulating a request as an object. Instead of calling a method, the Invoker creates a "Command" object that holds all the information needed to perform the action.

Here is a simple example of a light switch system:

from abc import ABC, abstractmethod

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

# The Concrete Command
class LightOnCommand(Command):
    def __init__(self, light):
        self.light = light

    def execute(self):
        self.light.turn_on()

# The Invoker
class RemoteControl:
    def __init__(self):
        self.command = None

    def set_command(self, command):
        self.command = command

    def press_button(self):
        self.command.execute()

Why this is powerful

By using an abstract Command interface, the RemoteControl doesn't need to know if it's turning on a light, adjusting a thermostat, or starting a security system. You can swap these commands out at runtime without changing the RemoteControl code.

Furthermore, because these commands are objects, you can easily add them to a list for queuing (like a macro) or store them in a stack to implement undo() functionality by defining an unexecute() method in your command interface. You are essentially turning a "procedural" function call into "data" that your application can manipulate, log, and schedule.

Key Takeaway: The Command Pattern promotes loose coupling by treating actions as first-class objects, allowing you to queue, log, and reverse operations without modifying the objects that trigger them.