将一个请求封装为一个对象,使发出请求的责任和执行请求的责任分割开。这样两者之间通过命令对象进行沟通,这样方便将命令对象进行存储,传递,调用,增加与管理。
饭店点餐:顾客把订单给服务员,服务员把订单给厨师,厨师做菜。
/**
* 抽象命令类
*/
public interface Command {
void execute();
}
/**
* 具体命令类
*/
public class OrderCommand implements Command{
// 持有接收者对象
private SeniorChef seniorChef;
private Order order;
public OrderCommand(SeniorChef seniorChef, Order order) {
this.seniorChef = seniorChef;
this.order = order;
}
@Override
public void execute() {
System.out.println(order.getDiningTable() + "卓的订单:");
Map<String, Integer> foodDir = order.getFoodDir();
Set<String> keys = foodDir.keySet();
for (String foodName : keys){
seniorChef.makeFood(foodName,foodDir.get(foodName));
}
System.out.println(order.getDiningTable() + "卓的饭好了---");
}
}
/**
* 订单类
*/
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 setFoodDir(Map<String, Integer> foodDir) {
this.foodDir = foodDir;
}
public void setFood(String name, int num) {
foodDir.put(name, num);
}
}
/**
* 厨师类
*/
public class SeniorChef {
public void makeFood(String name, int num){
System.out.println(num+"份"+name);
}
}
/**
* 服务员角色 请求者
*/
public class Waitor {
// 持有多个命令
private List<Command> commands = new ArrayList<>();
public List<Command> getCommands() {
return commands;
}
public void setCommands(Command command) {
commands.add(command);
}
// 发起命令的方法
public void orderUp(){
System.out.println("服务员说:新订单来了");
for (Command command : commands) {
if (command != null){
command.execute();
}
}
}
}
public class Test01 {
public static void main(String[] args) {
// 订单对象
Order order = new Order();
order.setDiningTable(1);
order.setFood("炒土豆丝",1);
order.setFood("可乐",1);
Order order1 = new Order();
order1.setDiningTable(2);
order1.setFood("面条", 1);
// 厨师对象
SeniorChef seniorChef = new SeniorChef();
// 创建命令对象
OrderCommand orderCommand = new OrderCommand(seniorChef, order);
OrderCommand orderCommand1 = new OrderCommand(seniorChef, order1);
// 创建调用者,服务员
Waitor waitor = new Waitor();
waitor.setCommands(orderCommand);
waitor.setCommands(orderCommand1);
// 发起命令
waitor.orderUp();
}
}