Appearance
可将请求转换为一个包含与请求相关的所有信息的独立对象。该转换让你能根据不同的请求将方法参数化、延迟请求执行或将其放入队列中,且能实现可撤销操作。此外,命令设计模式在web开发中不常见,常用于GUI的开发中。
需求分析
小米搬新家了,他想实现智能家居,开发一个app,可以控制家里的家电,比如控制空调的开关、加热、制冷等功能。利用命令设计模式,帮小米完成这个需求,注意:动作请求者就是手机app, 动作的执行者是家电的不同功能
编码实现
创建接收者
java
public class ConditionReceiver {
public void on(){
System.out.println("开启空调");
}
public void off(){
System.out.println("关闭空调");
}
public void cool(){
System.out.println("制冷模式");
}
public void warm(){
System.out.println("制热模式");
}
}
创建执行命令的抽象接口
java
public interface Command {
/**
* 执行动作
*/
void execute();
}
四个接口实现类
java
public class OnCommand implements Command{
/**
* 对哪个receiver进行命令调用
*/
private ConditionReceiver receiver;
public OnCommand(ConditionReceiver receiver) {
this.receiver = receiver;
}
@Override
public void execute() {
System.out.println("OnCommand -> execute");
receiver.on();
}
}
public class OffCommand implements Command{
/**
* 对哪个receiver进行命令调用
*/
private ConditionReceiver receiver;
public OffCommand(ConditionReceiver receiver) {
this.receiver = receiver;
}
@Override
public void execute() {
System.out.println("OffCommand -> execute");
receiver.off();
}
}
public class CoolCommand implements Command{
/**
* 对哪个receiver进行命令调用
*/
private ConditionReceiver receiver;
public CoolCommand(ConditionReceiver receiver) {
this.receiver = receiver;
}
@Override
public void execute() {
System.out.println("CoolCommand -> execute");
receiver.cool();
}
}
public class WarmCommand implements Command{
/**
* 对哪个receiver进行命令调用
*/
private ConditionReceiver receiver;
public WarmCommand(ConditionReceiver receiver) {
this.receiver = receiver;
}
@Override
public void execute() {
System.out.println("WarmCommand -> execute");
receiver.warm();
}
}
创建请求者
java
@Setter
public class AppInvoker {
private Command onCommand;
private Command offCommand;
private Command coolCommand;
private Command warmCommand;
public void on() {
onCommand.execute();
}
public void off() {
offCommand.execute();
}
public void warm() {
warmCommand.execute();
}
public void cool() {
coolCommand.execute();
}
}
使用
java
public static void main(String[] args) {
// 创建接收者,空调
ConditionReceiver receiver = new ConditionReceiver();
// 创建命令对象,设定命令接收者
Command onCommand = new OnCommand(receiver);
Command offCommand = new OffCommand(receiver);
Command coolCommand = new CoolCommand(receiver);
Command warmCommand = new WarmCommand(receiver);
// 创建请求者,把命令对象设置进去,app就是请求发起者
AppInvoker appInvoker = new AppInvoker();
appInvoker.setOnCommand(onCommand);
appInvoker.setOffCommand(offCommand);
appInvoker.setCoolCommand(coolCommand);
appInvoker.setWarmCommand(warmCommand);
// 发出命令
appInvoker.on();
appInvoker.cool();
}