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("空调开始制暖");
}
}
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 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 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 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();
}
}
public class Main {
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();
System.out.println();
appInvoker.cool();
System.out.println();
appInvoker.warm();
System.out.println();
appInvoker.off();
}
}