java 命令模式 例子
时间: 2023-05-18 18:06:02 浏览: 61
命令模式是一种行为设计模式,它将请求封装成一个对象,从而允许您将不同的请求、队列或日志请求参数化,并支持可撤销操作。以下是一个简单的 Java 命令模式示例:
```
// 命令接口
public interface Command {
void execute();
}
// 具体命令类
public class LightOnCommand implements Command {
private Light light;
public LightOnCommand(Light light) {
this.light = light;
}
public void execute() {
light.switchOn();
}
}
// 接收者类
public class Light {
public void switchOn() {
System.out.println("灯已打开");
}
public void switchOff() {
System.out.println("灯已关闭");
}
}
// 调用者类
public class RemoteControl {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void pressButton() {
command.execute();
}
}
// 客户端代码
public class Client {
public static void main(String[] args) {
Light light = new Light();
Command lightOnCommand = new LightOnCommand(light);
RemoteControl remoteControl = new RemoteControl();
remoteControl.setCommand(lightOnCommand);
remoteControl.pressButton();
}
}
```
在这个例子中,我们定义了一个 `Command` 接口,它有一个 `execute()` 方法,用于执行命令。然后我们实现了一个具体的命令类 `LightOnCommand`,它接收一个 `Light` 对象,并在 `execute()` 方法中调用 `Light` 对象的 `switchOn()` 方法。我们还定义了一个 `Light` 类作为接收者,它有 `switchOn()` 和 `switchOff()` 方法。最后,我们定义了一个 `RemoteControl` 类作为调用者,它有一个 `setCommand()` 方法用于设置命令,以及一个 `pressButton()` 方法用于执行命令。
在客户端代码中,我们创建了一个 `Light` 对象和一个 `LightOnCommand` 对象,并将 `LightOnCommand` 对象设置为 `RemoteControl` 对象的命令。然后我们调用 `RemoteControl` 对象的 `pressButton()` 方法,它会执行 `LightOnCommand` 对象的 `execute()` 方法,从而打开灯。