forked from duanbiaowu/go-examples-for-beginners
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuilder.go
97 lines (77 loc) · 1.24 KB
/
builder.go
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
85
86
87
88
89
90
91
92
93
94
95
96
97
package creational
type Builder interface {
WithColor(Color) Builder
WithWheels(Wheels) Builder
TopSpeed(Speed) Builder
Build() Car
}
type Car interface {
Drive() error
Stop() error
Color() Color
Wheels() Wheels
Speed() Speed
}
type Assembly struct {
color Color
wheels Wheels
speed Speed
}
type BMW struct {
color Color
wheels Wheels
speed Speed
}
type Speed float64
type Color string
type Wheels string
const (
MPH Speed = 1
KPH Speed = 1.60934
)
const (
BlueColor Color = "blue"
GreenColor Color = "green"
RedColor Color = "red"
)
const (
SportsWheels Wheels = "sports"
SteelWheels Wheels = "steel"
)
func (a *Assembly) WithColor(c Color) Builder {
a.color = c
return a
}
func (a *Assembly) WithWheels(w Wheels) Builder {
a.wheels = w
return a
}
func (a *Assembly) TopSpeed(s Speed) Builder {
a.speed = s
return a
}
func (a *Assembly) Build() Car {
return &BMW{
color: a.color,
wheels: a.wheels,
speed: a.speed,
}
}
func (b *BMW) Drive() error {
return nil
}
func (b *BMW) Stop() error {
return nil
}
func (b *BMW) Color() Color {
return b.color
}
func (b *BMW) Wheels() Wheels {
return b.wheels
}
func (b *BMW) Speed() Speed {
return b.speed
}
func NewBuilder() Builder {
return &Assembly{}
}