1 命令模式介绍
2 命令模式原理
3 命令模式实现
模拟酒店后厨的出餐流程,来对命令模式进行一个演示,命令模式角色的角色与案例中角色的对应关系如下:
服务员: 即调用者角色,由她来发起命令.
厨师: 接收者,真正执行命令的对象.
订单: 命令中包含订单
/*** 订单类**/
public class Order {private int diningTable; //餐桌号码private Map<String,Integer> foodMenu = new HashMap<>(); //存储菜名和份数public int getDiningTable() {return diningTable;}public void setDiningTable(int diningTable) {this.diningTable = diningTable;}public Map<String, Integer> getFoodMenu() {return foodMenu;}public void setFoodMenu(Map<String, Integer> foodMenu) {this.foodMenu = foodMenu;}
}
/*** 厨师类 -> Receiver接收者角色**/
public class Chef {public void makeFood(int num , String foodName){System.out.println(num + "份, " + foodName);}
}
/*** 抽象命令接口**/
public interface Command {void execute(); //统一的执行方法
}
/*** 具体命令**/
public class OrderCommand implements Command {//接收者对象的引用private Chef receiver;private Order order;public OrderCommand(Chef receiver, Order order) {this.receiver = receiver;this.order = order;}@Overridepublic void execute() {System.out.println(order.getDiningTable() + "桌的订单: ");Set<String> keySet = order.getFoodMenu().keySet();for (String key : keySet) {receiver.makeFood(order.getFoodMenu().get(key),key);}try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(order.getDiningTable() + "桌的菜品已经上齐!");}}
/*** 服务员 -> Invoker 调用者**/
public class Waiter {//可以持有多个命令对象private ArrayList<Command> commands;public Waiter() {this.commands = new ArrayList<>();}public Waiter(ArrayList<Command> commands) {this.commands = commands;}public void setCommand(Command command) {this.commands.add(command);}//发出指令public void orderUp(){System.out.println("叮咚! 服务员: 有新的订单,请师傅开始制作......");for (Command command : commands) {if(command != null){command.execute();}}}
}
public class Client {public static void main(String[] args) {Order order1 = new Order();order1.setDiningTable(10);order1.getFoodMenu().put("鲍鱼炒饭",1);order1.getFoodMenu().put("海参炒面",1);Order order2 = new Order();order2.setDiningTable(15);order2.getFoodMenu().put("回锅肉盖饭",1);order2.getFoodMenu().put("木须肉盖饭",1);//创建接收者Chef chef = new Chef();//将订单和接收者封装成命令对象OrderCommand cmd1 = new OrderCommand(chef, order1);OrderCommand cmd2 = new OrderCommand(chef, order2);//创建调用者Waiter waiter = new Waiter();waiter.setCommand(cmd1);waiter.setCommand(cmd2);//将订单发送给厨师 上菜waiter.orderUp();}
}
4 命令模式总结