package per.mjn.pattern.command;
import java.util.HashMap;
import java.util.Map;
// 订单类
public class Order {
// 餐桌号码
private int diningTable;
// 点的餐品和份数
private Map<String, Integer> foodDir = new HashMap<>();
public int getDiningTable() {
return diningTable;
}
public void setDiningTable(int diningTable) {
this.diningTable = diningTable;
}
public Map<String, Integer> getFoodDir() {
return foodDir;
}
public void setFood(String name, int num) {
foodDir.put(name, num);
}
}
package per.mjn.pattern.command;
// 厨师类
public class SeniorChef {
public void makeFood(String name, int num) {
System.out.println(num + "份" + name);
}
}
package per.mjn.pattern.command;
// 抽象命令类
public interface Command {
void execute();
}
package per.mjn.pattern.command;
import java.util.Map;
import java.util.Set;
// 具体的命令类
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() + "桌的订单:");
Map<String, Integer> foodDir = order.getFoodDir();
// 遍历map集合
Set<String> keys = foodDir.keySet();
for (String foodName : keys) {
receiver.makeFood(foodName, foodDir.get(foodName));
}
System.out.println(order.getDiningTable() + "桌的饭准备完毕!!!");
}
}
package per.mjn.pattern.command;
import java.util.ArrayList;
import java.util.List;
// 服务员类,属于调用者角色
public class Waiter {
// 持有多个命令对象
private List<Command> commands = new ArrayList<>();
public void setCommand(Command cmd) {
// 将cmd对象存储到list集合中
commands.add(cmd);
}
// 发起命令功能 喊 订单来了
public void orderUp() {
System.out.println("服务员说:大厨,新订单来了.");
// 遍历list集合
for (Command command : commands) {
if (command != null) {
command.execute();
}
}
}
}
package per.mjn.pattern.command;
public class Client {
public static void main(String[] args) {
// 创建第一个订单对象
Order order1 = new Order();
order1.setDiningTable(1);
order1.setFood("鸡翅", 2);
order1.setFood("小杯可乐", 2);
// 创建第二个订单对象
Order order2 = new Order();
order2.setDiningTable(2);
order2.setFood("鸡排", 2);
order2.setFood("小杯雪碧", 2);
// 创建接受者对象(厨师对象)
SeniorChef receiver = new SeniorChef();
// 创建命令对象
OrderCommand cmd1 = new OrderCommand(receiver, order1);
OrderCommand cmd2 = new OrderCommand(receiver, order2);
// 创建调用者(服务员对象)
Waiter waiter = new Waiter();
waiter.setCommand(cmd1);
waiter.setCommand(cmd2);
// 让服务员发起命令
waiter.orderUp();
}
}