命令模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import java.util.ArrayList;
import java.util.List;

interface Order {
void execute();
}

class Stock {

String name = "ABC";
int quantity = 10;

public void buy() {
System.out.println("Stock [ Name: " + name + ", Quantity: " + quantity + " ] bought");
}

public void sell() {
System.out.println("Stock [ Name: " + name + ", Quantity: " + quantity + " ] sold");
}
}

class BuyStock implements Order {
Stock abcStock;

public BuyStock(Stock abcStock) {
this.abcStock = abcStock;
}

public void execute() {
abcStock.buy();
}
}

class SellStock implements Order {
Stock abcStock;

public SellStock(Stock abcStock) {
this.abcStock = abcStock;
}

public void execute() {
abcStock.sell();
}
}

class Broker {
List<Order> orderList = new ArrayList<>();

public void takeOrder(Order order) {
orderList.add(order);
}

public void placeOrders() {
for (Order order : orderList) {
order.execute();
}
orderList.clear();
}
}

public class CommandPatternDemo {
public static void main(String[] args) {
Stock abcStock = new Stock();

BuyStock buyStockOrder = new BuyStock(abcStock);
SellStock sellStockOrder = new SellStock(abcStock);

Broker broker = new Broker();
broker.takeOrder(buyStockOrder);
broker.takeOrder(sellStockOrder);

broker.placeOrders();
}
}

命令模式
https://wangqian0306.github.io/2021/design-command-pattern/
作者
WangQian
发布于
2021年7月22日
许可协议