Featured image of post Java设计模式-命令模式Command

Java设计模式-命令模式Command

相关文章

【合集】Java设计模式

命令模式

订单类

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
@Data
public static class Order {
    // 餐桌号
    private int diningTable;
    // 菜品
    @Getter
    private final Map<String, Integer> foodDir = new HashMap<>();
    public void addFoodDic(String name, int num) {
        foodDir.put(name, num);
    }
}

请求者

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public static class Waiter {
    private final List<Command> commands = new ArrayList<>();
    public void setCommand(Command cmd) {
        commands.add(cmd);
    }
    public void orderUp() {
        System.out.println("美女服务员:大厨,新订单来了。。。。");
        for (Command command : commands) {
            if (command != null) {
                command.execute();
            }
        }
    }
}

命令接口

1
2
3
public interface Command {
    void execute();
}

具体命令 维护了命令接收者、订单

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
@AllArgsConstructor
public static class OrderCommand implements Command {
    private Receiver receiver;
    private Order order;
    public void execute() {
        System.out.println(order.getDiningTable() + "桌的订单:");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        order.getFoodDir().forEach((k, v) -> receiver.makeFood(k, v));
        System.out.println(order.getDiningTable() + "桌的饭准备完毕!!!");
    }
}

接收者

1
2
3
4
5
public static class Receiver {
    public void makeFood(String name, int num) {
        System.out.println(num + "份" + name);
    }
}

客户端调用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
Waiter request = new Waiter();
Receiver receiver = new Receiver();

Order order1 = new Order();
order1.setDiningTable(1);
order1.addFoodDic("西红柿鸡蛋面", 1);
order1.addFoodDic("小杯可乐", 2);
request.setCommand(new OrderCommand(receiver, order1));

Order order2 = new Order();
order2.setDiningTable(3);
order2.addFoodDic("尖椒肉丝盖饭", 1);
order2.addFoodDic("小杯雪碧", 1);
request.setCommand(new OrderCommand(receiver, order2));

request.orderUp();

输出

1
2
3
4
5
6
7
8
9
美女服务员:大厨,新订单来了。。。。
1桌的订单:
1份西红柿鸡蛋面
2份小杯可乐
1桌的饭准备完毕!!!
3桌的订单:
1份尖椒肉丝盖饭
1份小杯雪碧
3桌的饭准备完毕!!!

应用

{@link Runnable}就是一个抽象命令,{@link Thread}属于接收者,传入Runnable的实现类作为具体命令。也可以通过实现Runnable自己定义接收者。

皖ICP备2024056275号-1
发表了78篇文章 · 总计148.99k字
本站已稳定运行