Builder模式:使用简单的对象来构建复杂的对象;
Builder pattern separates the construction of a complex object from its representation so that the same construction process can create different representations.
生成器模式将复杂对象的结构与表示分开,以便相同的构建过程可以创建不同的表示形式。
In Go, normally a configuration struct is used to achieve the same behavior, however passing a struct to the builder method fills the code with boilerplate if cfg.Field != nil {…} checks.
在go里,通常配置结构来实现相同的行为,但是传递结构的制造方法充满样板代码 if cfg.Field != nil {…} 检查。
Implementation1
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
35package car
type Speed float64
const (
MPH Speed = 1
KPH = 1.60934
)
type Color string
const (
BlueColor Color = "blue"
GreenColor = "green"
RedColor = "red"
)
type Wheels string
const (
SportsWheels Wheels = "sports"
SteelWheels = "steel"
)
type Builder interface {
Color(Color) Builder
Wheels(Wheels) Builder
TopSpeed(Speed) Builder
Build() Interface
}
type Interface interface {
Drive() error
Stop() error
}
Usage1
2
3
4
5
6
7assembly := car.NewBuilder().Paint(car.RedColor)
familyCar := assembly.Wheels(car.SportsWheels).TopSpeed(50 * car.MPH).Build()
familyCar.Drive()
sportsCar := assembly.Wheels(car.SteelWheels).TopSpeed(150 * car.MPH).Build()
sportsCar.Drive()