命令模式(Command Pattern)是一种行为型设计模式,它将请求封装成一个对象,从而允许用户使用不同的请求、队列或日志来参数化其他对象。命令模式也支持可撤销的操作。

### 命令模式定义:
命令模式包含以下角色:
1. **命令(Command)**:定义执行操作的接口。
2. **具体命令(ConcreteCommand)**:实现命令接口,定义执行操作的方法。
3. **调用者(Invoker)**:负责调用命令对象执行请求。
4. **接收者(Receiver)**:知道如何实施与执行一个请求相关的操作。
5. **客户端(Client)**:创建一个具体命令对象,并设置其接收者。
### 命令模式例子:
假设有一个简单的家庭自动化系统,可以控制灯光的开关。以下是使用命令模式实现的例子:
1. **命令接口(Command)**:
```python
class Command:
def execute(self):
pass
```
2. **具体命令(ConcreteCommand)**:
```python
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()
```
3. **接收者(Receiver)**:
```python
class Light:
def turn_on(self):
print("Light is on")
def turn_off(self):
print("Light is off")
```
4. **调用者(Invoker)**:
```python
class RemoteControl:
def __init__(self):
self.command = None
def set_command(self, command):
self.command = command
def press_button(self):
self.command.execute()
```
5. **客户端(Client)**:
```python
# 创建接收者
light = Light()
# 创建具体命令对象
light_on_command = LightOnCommand(light)
light_off_command = LightOffCommand(light)
# 创建调用者并设置命令
remote = RemoteControl()
remote.set_command(light_on_command)
remote.press_button() # 输出:Light is on
remote.set_command(light_off_command)
remote.press_button() # 输出:Light is off
```
在这个例子中,`RemoteControl` 作为调用者,它通过 `set_command` 方法设置要执行的命令。当按下按钮时,它会调用命令对象的 `execute` 方法来执行相应的操作。这样,我们就可以通过改变命令对象来控制不同的操作,而不需要修改调用者的代码。
「点击下面查看原网页 领取您的八字精批报告☟☟☟☟☟☟」
本站内容仅供娱乐,请勿盲目迷信,侵权及不良内容联系邮箱:seoserver@126.com,一经核实,本站将立刻删除。