qingcheng-houduan/src/test/java/com/greenorange/promotion/light/CommandPatternExample.java

95 lines
2.1 KiB
Java
Raw Normal View History

2025-05-07 11:45:14 +00:00
package com.greenorange.promotion.light;
public class CommandPatternExample {
// 命令接口
public interface Command {
void execute();
}
// 接收者类:开灯
public static class Light {
public void on() {
System.out.println("灯已开启");
}
public void off() {
System.out.println("灯已关闭");
}
}
// 接收者类:开电视
public static class TV {
public void on() {
System.out.println("电视已开启");
}
public void off() {
System.out.println("电视已关闭");
}
}
// 具体命令类:开灯命令
public static class LightOnCommand implements Command {
private Light light;
public LightOnCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.on(); // 执行开灯操作
}
}
// 具体命令类:开电视命令
public static class TVOnCommand implements Command {
private TV tv;
public TVOnCommand(TV tv) {
this.tv = tv;
}
@Override
public void execute() {
tv.on(); // 执行开电视操作
}
}
// 调用者类:遥控器
public static class RemoteControl {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void pressButton() {
command.execute(); // 执行命令
}
}
// 测试类:命令模式的客户端
public static void main(String[] args) {
// 创建接收者
Light light = new Light();
TV tv = new TV();
// 创建命令
Command lightOn = new LightOnCommand(light);
Command tvOn = new TVOnCommand(tv);
// 创建遥控器
RemoteControl remote = new RemoteControl();
// 开灯
remote.setCommand(lightOn);
remote.pressButton(); // 输出: 灯已开启
// 开电视
remote.setCommand(tvOn);
remote.pressButton(); // 输出: 电视已开启
}
}