-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFlyWeight.dart
56 lines (43 loc) · 1.23 KB
/
FlyWeight.dart
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
import 'package:design_pattern_dart/Display/Example.dart';
class FlyWeight extends Example {
FlyWeight([String filePath = "lib/Structural/FlyWeight.dart"])
: super(filePath);
@override
String testRun() {
TeaMaker teaMaker = TeaMaker();
TeaShop shop = TeaShop(teaMaker);
shop.takeOrder("less sugar", 1);
shop.takeOrder("less ice", 2);
shop.takeOrder("add milk", 5);
return shop.serve();
}
}
class Tea {}
// 利用類似 factory 方式儲存 Tea 的 cache 減少記憶體的浪費
class TeaMaker {
Map<String, Tea> availableTea = {};
Tea make(String teaPreference) {
if (availableTea[teaPreference] == null) {
availableTea[teaPreference] = Tea();
}
return availableTea[teaPreference];
}
}
// teaMaker 在 makeTea 時就會先去找是否已經有做好的 tea 。
class TeaShop {
List<Tea> orders = List.filled(10, null);
TeaMaker _teaMaker;
TeaShop(this._teaMaker);
void takeOrder(String teaType, int index) {
orders[index] = _teaMaker.make(teaType);
}
String serve() {
String ordersResult = "";
orders.forEach((tea) {
if (tea != null) {
ordersResult += "Serving tea to table #${orders.indexOf(tea)}\n";
}
});
return ordersResult;
}
}