命令模式顾名思义不要去询问(Tell, Don’t Ask)”原则。
从字面意思讲,一个对象应该命令其他对象要干什么,而不是去查询其他对象状态再决定要做什么。
通过引入命令接口实现发起者和执行者之间的解耦;如果后期更换执行者,可以优雅的实现扩容,符合设计模式的开闭原则。但也增加的代码架构复杂度。
UML类图如下:(待更新)
代码如下:
package com.mp.mng.platform.command;
/**
* 命令模式 命令接口
*/
public interface Command {
public void execute(String foodName, int num);
}
package com.mp.mng.platform.command;
import org.assertj.core.util.Lists;
import java.util.List;
/**
* 具体命令执行类
*/
public class OrderCommand implements Command {
private ChiefReceiver chiefReceiver;
public OrderCommand(ChiefReceiver chiefReceiver) {
this.chiefReceiver = chiefReceiver;
}
@Override
public void execute(String foodName, int num) {
try {
chiefReceiver.doCook(foodName, num);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.mp.mng.platform.command;
/**
* 厨师类 接收者
*/
public class ChiefReceiver {
public void doCook(String foodName, int num) throws InterruptedException {
Thread.sleep(110);
System.out.println("食物:" + foodName + ",份数:" + num + "准备好了" );
}
}
package com.mp.mng.platform.command;
import org.assertj.core.util.Lists;
import java.util.List;
/**
* 服务员类 (命令发起者)
*/
public class Waiter {
private List<Command> list = Lists.newArrayList();
public void setCommand(Command command) {
list.add(command);
}
}
package com.mp.mng.platform.command;
/**
* 测试类
*/
public class Client {
public static void main(String[] args) {
ChiefReceiver receiver = new ChiefReceiver();
Command command = new OrderCommand(receiver);
command.execute("土豆丝盖浇饭", 1);
command.execute("豆浆", 1);
Command command2 = new OrderCommand(receiver);
command2.execute("番茄鸡蛋盖浇饭", 1);
command2.execute("可乐", 1);
Waiter waiter = new Waiter();
waiter.setCommand(command);
waiter.setCommand(command2);
}
}
最后执行效果: