1. 什么是命令模式?
命令模式是一种行为设计模式,它将请求封装为一个对象,从而使您能够使用不同的请求、队列或日志请求,以及支持可撤销操作。
命令模式的核心思想是将请求的发送者与请求的接收者解耦,使得两者之间的交互更加灵活。
1.1 命令模式的组成部分
命令模式通常包含以下几个组成部分,每个部分都有其特定的角色和功能。下面将详细介绍每个组成部分,并提供相应的代码示例。
1.1.1 命令接口(Command Interface)
命令接口定义了一个执行操作的接口,通常包含一个 execute
方法。所有具体命令类都需要实现这个接口。
# 命令接口
class Command:
def execute(self):
pass
1.1.2 具体命令类(Concrete Command)
具体命令类实现命令接口,定义与接收者之间的绑定关系,并调用接收者的相应操作。每个具体命令类都对应一个特定的操作。
# 接收者
class Light:
def turn_on(self):
print("The light is ON")
def turn_off(self):
print("The light is OFF")
# 具体命令类
class LightOnCommand(Command):
def __init__(self, light):
self.light = light
def execute(self):
self.light.turn_on()
class LightOffCommand(Command):
def __init__(self, light):
self.light = light
def execute(self):
self.light.turn_off()
1.1.3 接收者(Receiver)
接收者是具体的业务逻辑类,包含实际执行操作的方法。命令对象会调用接收者的方法来完成请求。
class Light:
def turn_on(self):
print("The light is ON")
def turn_off(self):
print("The light is OFF")
1.1.4 调用者(Invoker)
调用者持有命令对象并在适当的时候调用命令的 execute
方法。调用者不需要知道命令的具体实现,只需调用命令接口。
示例代码
class RemoteControl:
def __init__(self):
self.command = None
def set_command(self, command):
self.command = command
def press_button(self):
if self.command:
self.command.execute()
1.1.5 客户端(Client)
客户端负责创建具体命令对象并设置接收者。客户端代码通常会将命令对象传递给调用者。
if __name__ == "__main__":
# 创建接收者
light = Light()
# 创建具体命令
light_on = LightOnCommand(light)
light_off = LightOffCommand(light)
# 创建调用者
remote = RemoteControl()
# 开灯
remote.set_command(light_on)
remote.press_button() # 输出: The light is ON
# 关灯
remote.set_command(light_off)
remote.press_button() # 输出: The light is OFF
-
命令接口:定义了一个命令接口
Command
,包含一个execute
方法,所有具体命令类都需要实现这个方法。 -
具体命令类:
LightOnCommand
和LightOffCommand
实现了命令接口,分别用于打开和关闭灯。它们持有一个Light
对象的引用,并在execute
方法中调用相应的接收者方法。 -
接收者:
Light
类是接收者,包含实际执行操作的方法turn_on
和turn_off
。 -
调用者:
RemoteControl
类持有命令对象,并在适当的时候调用命令的execute
方法。它提供了set_command
方法来设置命令对象。 -
客户端代码:在客户端代码中,创建接收者、具体命令和调用者,并通过调用者执行命令。客户端代码不需要知道命令的具体实现,只需使用命令接口。
1.2 命令模式的优点
1.2.1 解耦
说明:命令模式通过将请求的发送者与接收者解耦,使得发送者不需要知道接收者的具体实现。这种解耦使得系统更加灵活,便于维护和扩展。
1. 灵活性:发送者可以在不修改代码的情况下替换接收者。
# 接收者
class Light:
def turn_on(self):
print("The light is ON")
def turn_off(self):
print("The light is OFF")
# 具体命令类
class LightOnCommand(Command):
def __init__(self, light):
self.light = light
def execute(self):
self.light.turn_on()
# 新的接收者
class Fan:
def turn_on(self):
print("The fan is ON")
def turn_off(self):
print("The fan is OFF")
# 客户端代码
light = Light()
fan = Fan()
light_on_command = LightOnCommand(light)
light_on_command.execute() # 输出: The light is ON
# 替换接收者
fan_on_command = LightOnCommand(fan) # 这里可以直接替换为 Fan
fan_on_command.execute() # 输出: The fan is ON
2. 可维护性:修改接收者的实现不会影响发送者。
# 修改接收者的实现
class Light:
def turn_on(self):
print("The light is now ON")
# 客户端代码
light = Light()
light_on_command = LightOnCommand(light)
light_on_command.execute() # 输出: The light is now ON
3. 可扩展性:轻松添加新命令而不修改现有代码。
# 新的具体命令类
class LightOffCommand(Command):
def __init__(self, light):
self.light = light
def execute(self):
self.light.turn_off()
# 客户端代码
light_off_command = LightOffCommand(light)
light_off_command.execute() # 输出: The light is OFF
4. 支持多种请求:可以处理不同类型的请求。
# 另一个具体命令类
class FanOnCommand(Command):
def __init__(self, fan):
self.fan = fan
def execute(self):
self.fan.turn_on()
# 客户端代码
fan_on_command = FanOnCommand(fan)
fan_on_command.execute() # 输出: The fan is ON
如果不采用解耦的设计,可能会面临以下风险:
1. 紧耦合:请求的发送者和接收者之间的紧耦合关系。
# 紧耦合示例
class RemoteControl:
def __init__(self):
self.light = Light() # 直接依赖于具体的接收者
def turn_on_light(self):
self.light.turn_on()
# 客户端代码
remote = RemoteControl()
remote.turn_on_light() # 输出: The light is ON
2. 难以扩展:添加新功能需要修改现有代码。
# 添加新功能需要修改现有代码
class RemoteControl:
def __init__(self):
self.light = Light()
self.fan = Fan() # 需要修改代码以添加新功能
def turn_on_light(self):
self.light.turn_on()
def turn_on_fan(self):
self.fan.turn_on()
# 客户端代码
remote = RemoteControl()
remote.turn_on_fan() # 输出: The fan is ON
1.2.2 可扩展性
说明:可以轻松添加新的命令,而不需要修改现有代码。只需创建新的命令类并实现命令接口即可。
示例代码
# 新的具体命令类
class FanOffCommand(Command):
def __init__(self, fan):
self.fan = fan
def execute(self):
self.fan.turn_off()
# 客户端代码
fan_off_command = FanOffCommand(fan)
fan_off_command.execute() # 输出: The fan is OFF
1.2.3 支持撤销操作
说明:可以通过维护命令的历史记录来实现撤销操作。每个命令对象可以记录其执行的状态,以便在需要时进行撤销。
示例代码
class CommandHistory:
def __init__(self):
self.history = []
def push(self, command):
self.history.append(command)
def pop(self):
if self.history:
return self.history.pop()
return None
# 客户端代码
history = CommandHistory()
# 执行命令
history.push(light_on_command)
light_on_command.execute() # 输出: The light is ON
# 撤销命令
last_command = history.pop()
if last_command:
print("Undoing last command...")
# 这里可以实现撤销逻辑,例如不绘制图形
1.2.4 支持队列请求
说明:可以将请求放入队列中,按顺序执行。这使得命令模式非常适合处理异步请求或批量操作。
示例代码
from collections import deque
class CommandQueue:
def __init__(self):
self.queue = deque()
def add_command(self, command):
self.queue.append(command)
def execute_commands(self):
while self.queue:
command = self.queue.popleft()
command.execute()
# 客户端代码
command_queue = CommandQueue()
command_queue.add_command(light_on_command)
command_queue.add_command(fan_on_command)
# 执行所有命令
command_queue.execute_commands()
# 输出:
# The light is ON
# The fan is ON
2. 示例 1:命令模式在文本编辑器中的应用
命令模式是一种强大的设计模式,能够有效地解耦请求的发送者与接收者,提高代码的灵活性和可维护性。在本文中,我们将通过一个文本编辑器的示例,展示如何使用命令模式来实现文本操作(如插入、删除和撤销)。
# 命令接口
class Command:
def execute(self):
pass
def undo(self):
pass
# 接收者
class TextEditor:
def __init__(self):
self.text = ""
def insert(self, text):
self.text += text
print(f"Inserted: '{text}' | Current text: '{self.text}'")
def delete(self, length):
deleted_text = self.text[-length:] if length <= len(self.text) else self.text
self.text = self.text[:-length]
print(f"Deleted: '{deleted_text}' | Current text: '{self.text}'")
# 具体命令类
class InsertCommand(Command):
def __init__(self, editor, text):
self.editor = editor
self.text = text
def execute(self):
self.editor.insert(self.text)
def undo(self):
self.editor.delete(len(self.text))
class DeleteCommand(Command):
def __init__(self, editor, length):
self.editor = editor
self.length = length
self.deleted_text = ""
def execute(self):
self.deleted_text = self.editor.text[-self.length:] if self.length <= len(
self.editor.text) else self.editor.text
self.editor.delete(self.length)
def undo(self):
self.editor.insert(self.deleted_text)
# 调用者
class CommandHistory:
def __init__(self):
self.history = []
def push(self, command):
self.history.append(command)
def pop(self):
if self.history:
return self.history.pop()
return None
class CommandQueue:
def __init__(self):
self.queue = []
def add_command(self, command):
self.queue.append(command)
def execute_commands(self, history):
while self.queue:
command = self.queue.pop(0)
command.execute()
history.push(command) # 将执行的命令添加到历史记录中
# 客户端代码
if __name__ == "__main__":
# 创建接收者
editor = TextEditor()
history = CommandHistory()
command_queue = CommandQueue()
# 创建并执行插入命令
print("Executing insert commands:")
insert_command1 = InsertCommand(editor, "Hello, ")
command_queue.add_command(insert_command1)
insert_command2 = InsertCommand(editor, "World!")
command_queue.add_command(insert_command2)
# 执行所有命令并记录到历史
command_queue.execute_commands(history)
# 预期输出: "Inserted: 'Hello, ' | Current text: 'Hello, '"
# 预期输出: "Inserted: 'World!' | Current text: 'Hello, World!'"
print(f"Current text after insertions: '{editor.text}'") # 输出: Hello, World!
# 撤销最后一个命令(插入)
print("\nUndoing last insert command:")
last_command = history.pop()
if last_command:
last_command.undo() # 撤销插入操作
# 预期输出: "Deleted: 'World!' | Current text: 'Hello, '"
print(f"Current text after undo: '{editor.text}'") # 输出: Hello,
# 创建并执行删除命令
print("\nExecuting delete command:")
delete_command = DeleteCommand(editor, 6)
command_queue.add_command(delete_command)
command_queue.execute_commands(history)
# 预期输出: "Deleted: 'Hello, ' | Current text: ''"
print(f"Current text after deletion: '{editor.text}'") # 输出: (空字符串)
# 撤销删除命令
print("\nUndoing delete command:")
last_command = history.pop()
if last_command:
last_command.undo() # 撤销删除操作
# 预期输出: "Inserted: 'Hello, ' | Current text: 'Hello, '"
print(f"Current text after undo delete: '{editor.text}'") # 输出: Hello,
# 最终状态
print(f"\nFinal text: '{editor.text}'") # 输出最终文本状态
Executing insert commands:
Inserted: 'Hello, ' | Current text: 'Hello, '
Inserted: 'World!' | Current text: 'Hello, World!'
Current text after insertions: 'Hello, World!'
Undoing last insert command:
Deleted: 'World!' | Current text: 'Hello, '
Current text after undo: 'Hello, '
Executing delete command:
Deleted: 'ello, ' | Current text: 'H'
Current text after deletion: 'H'
Undoing delete command:
Inserted: 'ello, ' | Current text: 'Hello, '
Current text after undo delete: 'Hello, '
Final text: 'Hello, '
-
命令接口:定义了一个命令接口
Command
,包含execute
和undo
方法。所有具体命令类都需要实现这两个方法。 -
接收者:
TextEditor
类是接收者,包含实际执行操作的方法insert
和delete
。这些方法负责修改文本状态并输出当前文本。 -
具体命令类:
InsertCommand
用于插入文本。它持有一个TextEditor
对象的引用,并在execute
方法中调用insert
方法。在undo
方法中调用delete
方法以撤销插入操作。DeleteCommand
用于删除文本。它同样持有一个TextEditor
对象的引用,并在execute
方法中调用delete
方法。在undo
方法中调用insert
方法以撤销删除操作。
-
调用者:
CommandHistory
类用于维护命令的历史记录,以支持撤销操作。它提供push
和pop
方法来管理命令历史。CommandQueue
类用于将命令放入队列中,按顺序执行,并在执行时将命令添加到历史记录中。
-
客户端代码:在客户端代码中,创建接收者、具体命令和调用者,并通过调用者执行命令。每个执行的命令都会被记录到
CommandHistory
中,以便后续撤销。