题目
介绍下命令模式
答案
命令模式(Command Pattern)将请求封装为对象,从而允许参数化客户端、队列请求、日志请求操作。
适用场景:
- 需要将请求发送者和接收者解耦。
- 实现操作的撤销、重做等功能。
示例:遥控器控制灯
```java
// 命令接口
interface Command {
void execute();
}
// 接收者
class Light {
public void on() {
System.out.println("Light is ON");
}
public void off() {
System.out.println("Light is OFF");
}
}
// 具体命令
class LightOnCommand implements Command {
private Light light;
public LightOnCommand(Light light) { this.light = light; }
public void execute() { light.on(); }
}
// 调用者
class RemoteControl {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void pressButton() {
command.execute();
}
}
// 测试
public class CommandTest {
public static void main(String[] args) {
Light light = new Light();
Command command = new LightOnCommand(light);
RemoteControl control = new RemoteControl();
control.setCommand(command);
control.pressButton();
}
}
```
