现有一种空调支持3种运行模式制冷模式CoolMode制热模式HotMode和自动模式AutoMode在遥控器上选择制冷模式再设置温度时空调将送出冷风;选择制热模式再设置温度时空调将送出热风。选择自动模式在设置温度时空调将根据室温和设置温度的差异来选择输入热风或者冷风。请选择命令模式来模拟该空调遥控器控制空调的过程并java模拟实现。
首先,我们需要定义一个命令接口,其中包含了执行命令的方法execute()。
public interface Command {
void execute();
}
接下来,我们定义三个具体的命令类,分别对应空调的三种运行模式。
public class CoolModeCommand implements Command {
private AirConditioner airConditioner;
public CoolModeCommand(AirConditioner airConditioner) {
this.airConditioner = airConditioner;
}
@Override
public void execute() {
airConditioner.setMode(Mode.CoolMode);
}
}
public class HotModeCommand implements Command {
private AirConditioner airConditioner;
public HotModeCommand(AirConditioner airConditioner) {
this.airConditioner = airConditioner;
}
@Override
public void execute() {
airConditioner.setMode(Mode.HotMode);
}
}
public class AutoModeCommand implements Command {
private AirConditioner airConditioner;
private int temperature;
public AutoModeCommand(AirConditioner airConditioner, int temperature) {
this.airConditioner = airConditioner;
this.temperature = temperature;
}
@Override
public void execute() {
airConditioner.setMode(Mode.AutoMode);
airConditioner.setTemperature(temperature);
}
}
其中,CoolModeCommand和HotModeCommand只需要设置空调的运行模式为对应的模式即可。AutoModeCommand除了设置运行模式外,还需要设置温度。
最后,我们定义遥控器类,该类包含了一个命令对象,可以通过setCommand()方法来设置命令对象,并通过executeCommand()方法来执行命令。
public class RemoteController {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void executeCommand() {
command.execute();
}
}
在实际使用中,我们可以通过如下方式来控制空调:
AirConditioner airConditioner = new AirConditioner();
RemoteController remoteController = new RemoteController();
// 选择制冷模式
Command coolModeCommand = new CoolModeCommand(airConditioner);
remoteController.setCommand(coolModeCommand);
remoteController.executeCommand();
// 设置温度
airConditioner.setTemperature(25);
// 选择制热模式
Command hotModeCommand = new HotModeCommand(airConditioner);
remoteController.setCommand(hotModeCommand);
remoteController.executeCommand();
// 设置温度
airConditioner.setTemperature(20);
// 选择自动模式
Command autoModeCommand = new AutoModeCommand(airConditioner, 22);
remoteController.setCommand(autoModeCommand);
remoteController.executeCommand();
``
原文地址: https://www.cveoy.top/t/topic/cFLb 著作权归作者所有。请勿转载和采集!