命令模式(Command Pattern)是一种行为型设计模式,它将请求封装成对象,从而使得可以用不同的请求对客户进行参数化,对请求排队或记录请求日志,以及支持可撤销的操作。

命令模式包含以下主要角色:

1. 命令接口(Command): 声明了执行命令的接口,通常包含一个 execute 方法。

2. 具体命令类(ConcreteCommand): 实现了命令接口,负责具体的命令执行。

3. 调用者(Invoker): 负责调用命令对象执行请求,它不知道具体的命令细节,只知道调用命令对象的 execute 方法。

4. 接收者(Receiver): 实际执行命令的对象,知道如何实现具体的业务逻辑。

5. 客户端(Client): 创建命令对象,并设置命令的接收者。客户端决定哪些命令被执行。

下面是一个简单的命令模式的例子,假设我们有一个遥控器,可以通过按钮来控制一些家电设备:
# 命令接口
class Command:
    def execute(self):
        pass

# 具体命令类:开灯命令
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()

# 接收者:灯
class Light:
    def turn_on(self):
        print("Light is ON")

    def turn_off(self):
        print("Light is OFF")

# 调用者:遥控器
class RemoteControl:
    def __init__(self):
        self._command = None

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

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

# 客户端代码
if __name__ == "__main__":
    # 创建灯和命令对象
    light = Light()
    light_on_command = LightOnCommand(light)
    light_off_command = LightOffCommand(light)

    # 创建遥控器
    remote = RemoteControl()

    # 设置命令并执行
    remote.set_command(light_on_command)
    remote.press_button()

    remote.set_command(light_off_command)
    remote.press_button()

在上述示例中,Command 是命令接口,LightOnCommand 和 LightOffCommand 是具体命令类。Light 是接收者,负责实际执行开灯和关灯操作。RemoteControl 是调用者,通过设置不同的命令对象来执行相应的命令。

命令模式的优点在于它将请求的发送者和接收者解耦,使得可以轻松添加新的命令和接收者。这种模式支持撤销操作和事务的实现,同时也使得可以实现日志记录、队列请求等功能。


转载请注明出处:http://www.zyzy.cn/article/detail/11852/设计模式