Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Command Pattern

Python Command Pattern

The Command Pattern is a behavioral design pattern that encapsulates a request as an object, thereby letting you parameterize clients with different requests. In short,the Command Pattern wraps operations (such as opening a file or saving data) into independent objects, allowing you to handle operations just like data.

A Real-Life Analogy

Imagine the ordering process in a restaurant:

This pattern with a clear division of labor is the real-life embodiment of the Command Pattern.


Why Do We Need the Command Pattern

Limitations of the Traditional Approach

In traditional programming, we usually call an object's methods directly:

Example

class

Light:

   

def

turn_on

(

self

)

:

       

print

(

"The light is on"

)

   

   

def

turn_off

(

self

)

:

       

print

(

"The light is off"

)

Directly calling

light

=

Light

(

)

light.

turn_on

(

)

light.

turn_off

(

)

This approach has several problems:

  1. Tight coupling: the invoker needs to know the receiver's concrete interface
  2. Hard to extend: adding new features requires modifying existing code
  3. No support for undo/redo: operations cannot be rolled back after execution

Advantages of the Command Pattern

The Command Pattern solves the above problems by introducing an intermediate layer (the command object), providing:


Core Components of the Command Pattern

Basic structure

The Command Pattern contains four core roles:

Role Responsibility Example
Command(Command interface) Declares the interface for executing an operation execute(), undo()
ConcreteCommand(Concrete command) Implements the command interface and binds the receiver LightOnCommand, LightOffCommand
Receiver(Receiver) Knows how to perform the operation Light, TV
Invoker(Invoker) Stores and executes commands RemoteControl

Complete Code Example

Basic Implementation

Let's understand the Command Pattern through a smart home lighting control example:

Example

from

abc

import

ABC

,

abstractmethod

from

typing

import

List

1. Command Interface

class

Command

(

ABC

)

:

   

@

abstractmethod

   

def

execute

(

self

)

:

       

pass

   

   

@

abstractmethod

   

def

undo

(

self

)

:

       

pass

2. Receiver - Light Device

class

Light:

   

def

turn_on

(

self

)

:

       

print

(

"💡 Light is on"

)

   

   

def

turn_off

(

self

)

:

       

print

(

"💡 Light is off"

)

3. Concrete Command - Light On Command

class

LightOnCommand

(

Command

)

:

   

def

init

(

self

,

light: Light

)

:

       

self

.

light

=

light

   

   

def

execute

(

self

)

:

       

self

.

light

.

turn_on

(

)

   

   

def

undo

(

self

)

:

       

self

.

light

.

turn_off

(

)

4. Concrete Command - Light Off Command

class

LightOffCommand

(

Command

)

:

   

def

init

(

self

,

light: Light

)

:

       

self

.

light

=

light

   

   

def

execute

(

self

)

:

       

self

.

light

.

turn_off

(

)

   

   

def

undo

(

self

)

:

       

self

.

light

.

turn_on

(

)

5. Invoker - Remote Control

class

RemoteControl:

   

def

init

(

self

)

:

       

self

.

command

=

None

       

self

.

history

: List

[

Command

]

=

[

]

   

   

def

set_command

(

self

,

command: Command

)

:

       

self

.

command

=

command

   

   

def

press_button

(

self

)

:

       

if

self

.

command

:

           

self

.

command

.

execute

(

)

           

self

.

history

.

append

(

self

.

command

)

   

   

def

press_undo

(

self

)

:

       

if

self

.

history

:

            last_command

=

self

.

history

.

pop

(

)

            last_command.

undo

(

)

Client code

if

name

==

"main"

:

   

Create the device

    living_room_light

=

Light

(

)

   

   

Create commands

    light_on

=

LightOnCommand

(

living_room_light

)

    light_off

=

LightOffCommand

(

living_room_light

)

   

   

Create the remote control

    remote

=

RemoteControl

(

)

   

   

Test turning on the light

   

print

(

"=== Test Light On ==="

)

    remote.

set_command

(

light_on

)

    remote.

press_button

(

)

   

   

Test turning off the light

   

print

(

"\n=== Test Light Off ==="

)

    remote.

set_command

(

light_off

)

    remote.

press_button

(

)

   

   

Test undo

   

print

(

"\n=== Test Undo Operation ==="

)

    remote.

press_undo

(

)

 

Undo turning off the light, should turn the light on

    remote.

press_undo

(

)

 

Undo turning on the light, should turn the light off

Running result:


Advanced Application Example

A universal remote control supporting multiple devices

Let's extend the previous example to create a universal remote control that supports multiple devices:

Example

Add a new device - TV

class

TV:

   

def

init

(

self

,

location:

str

)

:

       

self

.

location

=

location

       

self

.

is_on

=

False

       

self

.

volume

=

50

   

   

def

turn_on

(

self

)

:

       

self

.

is_on

=

True

       

print

(

f

"📺 {self.location}TV is on"

)

   

   

def

turn_off

(

self

)

:

       

self

.

is_on

=

False

       

print

(

f

"📺 {self.location}TV is off"

)

   

   

def

set_volume

(

self

,

volume:

int

)

:

       

self

.

volume

=

volume

       

print

(

f

"📺 {self.location}TV volume set to {volume}"

)

TV-related commands

class

TVOnCommand

(

Command

)

:

   

def

init

(

self

,

tv: TV

)

:

       

self

.

tv

=

tv

       

self

.

previous_volume

=

50

   

   

def

execute

(

self

)

:

       

self

.

previous_volume

=

self

.

tv

.

volume

       

self

.

tv

.

turn_on

(

)

   

   

def

undo

(

self

)

:

       

self

.

tv

.

turn_off

(

)

       

self

.

tv

.

volume

=

self

.

previous_volume

class

TVVolumeUpCommand

(

Command

)

:

   

def

init

(

self

,

tv: TV

)

:

       

self

.

tv

=

tv

       

self

.

previous_volume

=

50

   

   

def

execute

(

self

)

:

       

self

.

previous_volume

=

self

.

tv

.

volume

       

self

.

tv

.

set_volume

(

min

(

100

,

self

.

tv

.

volume

10

)

)

   

   

def

undo

(

self

)

:

       

self

.

tv

.

set_volume

(

self

.

previous_volume

)

Macro command - execute multiple commands with one button

class

MacroCommand

(

Command

)

:

   

def

init

(

self

,

commands

: List

[

Command

]

)

:

       

self

.

commands

=

commands

   

   

def

execute

(

self

)

:

       

for

command

in

self

.

commands

:

            command.

execute

(

)

   

   

def

undo

(

self

)

:

       

Undo in reverse order

       

for

command

in

reversed

(

self

.

commands

)

:

            command.

undo

(

)

Improved remote control

class

AdvancedRemoteControl:

   

def

init

(

self

,

slot_count:

int

=

4

)

:

       

self

.

on_commands

: List

[

Command

]

=

[

None

]

       

self

.

off_commands

: List

[

Command

]

=

[

None

]

       

self

.

history

: List

[

Command

]

=

[

]

   

   

def

set_command

(

self

,

slot:

int

,

on_command: Command

,

off_command: Command

)

:

       

self

.

on_commands

[

slot

]

=

on_command

       

self

.

off_commands

[

slot

]

=

off_command

   

   

def

press_on_button

(

self

,

slot:

int

)

:

       

if

self

.

on_commands

[

slot

]

:

           

self

.

on_commands

[

slot

]

.

execute

(

)

           

self

.

history

.

append

(

self

.

on_commands

[

slot

]

)

   

   

def

press_off_button

(

self

,

slot:

int

)

:

       

if

self

.

off_commands

[

slot

]

:

           

self

.

off_commands

[

slot

]

.

execute

(

)

           

self

.

history

.

append

(

self

.

off_commands

[

slot

]

)

   

   

def

press_undo

(

self

)

:

       

if

self

.

history

:

            last_command

=

self

.

history

.

pop

(

)

            last_command.

undo

(

)

Test the advanced remote control

def

test_advanced_remote

(

)

:

   

print

(

"=== Test Universal Remote Control ==="

)

   

   

Create the device

    living_room_light

=

Light

(

)

    bedroom_tv

=

TV

(

"Bedroom"

)

   

   

Create commands

    light_on

=

LightOnCommand

(

living_room_light

)

    light_off

=

LightOffCommand

(

living_room_light

)

    tv_on

=

TVOnCommand

(

bedroom_tv

)

    tv_volume_up

=

TVVolumeUpCommand

(

bedroom_tv

)

   

   

Create a macro command - theater mode

    cinema_mode

=

MacroCommand

(

[

light_off

,

tv_on

,

tv_volume_up

]

)

   

   

Set up the remote control

    remote

=

AdvancedRemoteControl

(

)

    remote.

set_command

(

0

,

light_on

,

light_off

)

     

Slot 0: lighting control

    remote.

set_command

(

1

,

tv_on

,

TVOnCommand

(

bedroom_tv

)

)

 

Slot 1: TV control

    remote.

set_command

(

2

,

cinema_mode

,

light_on

)

   

Slot 2: theater mode

   

   

Test various functions

   

print

(

"\n1. Turn on the light:"

)

    remote.

press_on_button

(

0

)

   

   

print

(

"\n2. Enable theater mode:"

)

    remote.

press_on_button

(

2

)

   

   

print

(

"\n3. Undo operation:"

)

    remote.

press_undo

(

)

if

name

==

"main"

:

    test_advanced_remote

(

)


Parameters and Options of the Command Pattern

Extensions of the Command Interface

In real applications, the command interface can be extended with more features as needed:

Example

class

AdvancedCommand

(

ABC

)

:

   

@

abstractmethod

   

def

execute

(

self

)

:

       

"""Execute command"""

       

pass

   

   

@

abstractmethod

   

def

undo

(

self

)

:

       

"""Undo command"""

       

pass

   

   

@

abstractmethod

   

def

redo

(

self

)

:

       

"""Redo command"""

       

pass

   

   

@

abstractmethod

   

def

can_execute

(

self

)

bool

:

       

"""Check whether the command can be executed"""

       

pass

   

   

@

abstractmethod

   

def

get_description

(

self

)

str

:

       

"""Get command description"""

       

pass

Command Queue and Delayed Execution

The Command Pattern naturally supports command queues, which is very useful in many scenarios:

Example

class

CommandQueue:

   

def

init

(

self

)

:

       

self

.

queue

: List

[

Command

]

=

[

]

   

   

def

add_command

(

self

,

command: Command

)

:

       

self

.

queue

.

append

(

command

)

   

   

def

process_commands

(

self

)

:

       

while

self

.

queue

:

            command

=

self

.

queue

.

pop

(

0

)

           

if

command.

can_execute

(

)

:

                command.

execute

(

)

   

   

def

clear

(

self

)

:

       

self

.

queue

.

clear

(

)


Practical Exercise

Exercise 1: Implement an Air Conditioner Control System

Try to implement the Command Pattern for an air conditioner control system:

Example

Your code here

class

AirConditioner:

   

def

init

(

self

)

:

       

self

.

temperature

=

26

       

self

.

is_on

=

False

   

   

def

turn_on

(

self

)

:

       

Implement turning on the air conditioner

       

pass

   

   

def

turn_off

(

self

)

:

       

Implement turning off the air conditioner

       

pass

   

   

def

set_temperature

(

self

,

temp:

int

)

:

       

Implement setting the temperature

       

pass

Implement air-conditioner-related command classes

AirConditionerOnCommand

AirConditionerOffCommand  

TemperatureUpCommand

TemperatureDownCommand

Exercise 2: Implement Undo for a Text Editor

Create a simple text editor that supports typing text and undo:

Example

class

TextEditor:

   

def

init

(

self

)

:

       

self

.

content

=

""

   

   

def

add_text

(

self

,

text:

str

)

:

       

Implement adding text

       

pass

   

   

def

delete_text

(

self

,

length:

int

)

:

       

Implement deleting text

       

pass

Implement text editing commands

AddTextCommand

DeleteTextCommand


Frequently Asked Questions

Q: What scenarios is the Command Pattern suitable for?

A: The Command Pattern is especially suitable for the following scenarios:

Q: What are the disadvantages of the Command Pattern?

A: The main disadvantages include:

Q: How to decide whether to use the Command Pattern?

A: Consider the following points:


Summary

By encapsulating operations as objects, the Command Pattern decouples the invoker from the receiver and provides powerful extensibility. Although it adds some code complexity, in scenarios requiring undo/redo, operation queues, and logging, the Command Pattern is an indispensable design pattern.

Key points: