-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand_stock_order_example.dart
More file actions
84 lines (63 loc) · 1.99 KB
/
command_stock_order_example.dart
File metadata and controls
84 lines (63 loc) · 1.99 KB
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
75
76
77
78
79
80
81
82
83
84
import 'dart:developer';
/// We have created an interface Order which is acting as a command.
/// We have created a Stock class which acts as a request.
/// We have concrete command classes BuyStock and SellStock implementing Order interface
/// which will do actual command processing.
/// A class Broker is created which acts as an invoker object.
/// It can take and place orders.
/// Broker object uses command pattern to identify which object will execute which command based on the type of command.
/// CommandPatternDemo, our demo class, will use Broker class to demonstrate command pattern.
/// Step 1
/// Create a command interface.
abstract interface class Order {
void execute();
}
/// Step 2
/// Create a request class.
class Stock {
String _name = "ABC";
int _quantity = 10;
void buy() => log("Stock [ Name: $_name, Quantity: $_quantity bought");
void sell() => log("Stock [ Name: $_name, Quantity: $_quantity sold");
}
/// Step 3
/// Create concrete classes implementing the Order interface.
class BuyStock implements Order {
Stock _stock;
BuyStock(this._stock);
void execute() => _stock.buy();
}
class SellStock implements Order {
Stock _stock;
SellStock(this._stock);
void execute() => _stock.sell();
}
/// Step 4
/// Create command invoker (Sender) class.
class Broker {
List<Order> _orderList = [];
void takeOrder(Order order) => _orderList.add(order);
void placeOrders() {
for (Order order in _orderList) {
order.execute();
}
_orderList.clear();
}
}
/// Step 5
/// Use the Broker class to take and execute commands.
void main() {
Stock abcStock = Stock();
/// Commands
BuyStock buyStockOrder = BuyStock(abcStock);
SellStock sellStockOrder = SellStock(abcStock);
/// Invoker -> Sender
Broker broker = Broker();
broker.takeOrder(buyStockOrder);
broker.takeOrder(sellStockOrder);
broker.placeOrders();
}
/// Step 6
// Verify the output.
/// Stock [ Name: ABC, Quantity: 10 ] bought
/// Stock [ Name: ABC, Quantity: 10 ] sold