-
Notifications
You must be signed in to change notification settings - Fork 6
/
Builder.dart
83 lines (68 loc) · 1.76 KB
/
Builder.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
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
import '../example.dart';
class Burger {
double _size;
bool _cheese;
bool _beef;
bool _lettuce;
bool _tomato;
// Not good: Burger(this._size, this._cheese, this._beef, this._lettuce, this._tomato);
// 把所有的属性都挤在了构造参数里
//good: 将实例复杂属性配置下放到builder中,由builder来处理
Burger(BurgerBuilder builder) {
_size = builder._size;
_cheese = builder._cheese;
_beef = builder._beef;
_lettuce = builder._lettuce;
_tomato = builder._tomato;
}
String content() => """
Your Burger size: $_size,
Cheese: $_cheese,
Beef: $_beef,
Lettuce: $_lettuce,
Tomato: $_tomato.
""";
}
// 利用 Builder 中方法來多步配置实例,并通过 build 方法构建目标实体
// 配置方法返回 builder 本身(this)来连续配置属性
// BurgerBuilder().addCheese().addBeef().build();
class BurgerBuilder {
double _size;
bool _cheese = false;
bool _beef = false;
bool _lettuce = false;
bool _tomato = false;
BurgerBuilder(this._size);
BurgerBuilder addCheese() {
_cheese = true;
return this;
}
BurgerBuilder addBeef() {
_beef = true;
return this;
}
BurgerBuilder addLettuce() {
_lettuce = true;
return this;
}
BurgerBuilder addTomato() {
_tomato = true;
return this;
}
Burger build() => Burger(this);
}
class Builder extends Example {
Builder([String filePath = "src/Creational/Builder.dart"]) : super(filePath);
@override
String testRun() {
var noLettuceBurger =
BurgerBuilder(15).addBeef().addCheese().addTomato().build();
return noLettuceBurger.content();
// Builder👇👇👇
// Your Burger size: 15.0,
// Cheese: true,
// Beef: true,
// Lettuce: false,
// Tomato: true.
}
}