命令设计模式代码实现
时间: 2023-10-15 14:04:44 浏览: 47
命令设计模式是一种行为型设计模式,它允许将请求封装成一个对象,从而使不同的请求能够在客户端之间进行参数化。下面是一个简单的命令设计模式的代码实现示例:
```python
# 命令接口
class Command:
def execute(self):
pass
# 具体命令类
class LightOnCommand(Command):
def __init__(self, light):
self.light = light
def execute(self):
self.light.on()
class LightOffCommand(Command):
def __init__(self, light):
self.light = light
def execute(self):
self.light.off()
# 接收者类
class Light:
def on(self):
print("灯已打开")
def off(self):
print("灯已关闭")
# 调用者(遥控器)类
class RemoteControl:
def __init__(self):
self.commands = []
def add_command(self, command):
self.commands.append(command)
def execute_commands(self):
for command in self.commands:
command.execute()
# 客户端代码
if __name__ == '__main__':
light = Light()
light_on_command = LightOnCommand(light)
light_off_command = LightOffCommand(light)
remote_control = RemoteControl()
remote_control.add_command(light_on_command)
remote_control.add_command(light_off_command)
remote_control.execute_commands()
```
在上面的示例中,我们定义了一个命令接口 `Command`,并实现了两个具体的命令类 `LightOnCommand` 和 `LightOffCommand`。这些具体命令类都实现了 `execute` 方法,用于执行相应的操作。`Light` 类是接收者类,它定义了真正执行操作的方法。`RemoteControl` 类是调用者类,它可以添加命令并执行它们。
在客户端代码中,我们创建了一个 `Light` 对象,并为它定义了打开和关闭的命令。然后,我们创建了一个遥控器对象 `RemoteControl`,并将命令添加到它里面。最后,我们调用 `execute_commands` 方法,执行所有添加的命令。
这就是一个简单的命令设计模式的代码实现示例。当然,实际应用可以更加复杂,可以根据具体需求进行扩展和修改。