设计模式 命令模式
概念
命令符合下面这个场景


结构

案例


定义一个执行接口:
public interface Command {
void execute();
}
定义订单类
@Data
public class Order {
//餐桌号码
private int diningTable;
//用来存储餐名以及份数
private Map<String,Integer> foodDic = new HashMap<>();
}
定义接受者 大厨类
public class SeniorChef {
public void makeFood(int num,String foodName){
System.out.println(num + "份" + foodName);
}
}
定义命令对象 集成订单和大厨
public class OrderCommand implements Command{
private SeniorChef receiver;
private Order order;
public OrderCommand(SeniorChef receiver, Order order) {
this.receiver = receiver;
this.order = order;
}
@Override
public void execute() {
System.out.println(order.getDiningTable() + "桌的订单:");
Set<String> keys = order.getFoodDic().keySet();
for(String key : keys){
receiver.makeFood(order.getFoodDic().get(key),key);
}
System.out.println(order.getDiningTable() + "桌的饭做好了");
}
}
定义发布命令者 服务器
public class Waiter {
private ArrayList<Command> commands;
public Waiter(ArrayList<Command> commands) {
this.commands = commands;
}
public void addCommand(Command command){
commands.add(command);
}
//发出命令 喊订单来了 厨师开始执行
public void orderUp(){
System.out.println("服务员:订单来了");
for (int i = 0; i < commands.size(); i++) {
Command cmd = commands.get(i);
if(cmd != null){
cmd.execute();
}
}
}
}
测试使用:
public class Client {
public static void main(String[] args) {
//创建两个order
Order order1 = new Order();
order1.setDiningTable(1);
order1.getFoodDic().put("西红柿炒鸡蛋",1);
order1.getFoodDic().put("小杯可乐",2);
Order order2 = new Order();
order2.setDiningTable(2);
order2.getFoodDic().put("漏丸",1);
order2.getFoodDic().put("雪碧",1);
//创建接收者
SeniorChef receiver = new SeniorChef();
//将订单和接收者(厨师)封装成命令对象
}
}

浙公网安备 33010602011771号