Skip to content

Commit e7af050

Browse files
committedFeb 22, 2017
creational/builder: implement the builder pattern
1 parent 4595241 commit e7af050

File tree

2 files changed

+62
-1
lines changed

2 files changed

+62
-1
lines changed
 

‎README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ A curated collection of idiomatic design & application patterns for Go language.
1616
| Pattern | Description | Status |
1717
|:-------:|:----------- |:------:|
1818
| [Abstract Factory](/creational/abstract_factory.md) | Provides an interface for creating families of releated objects ||
19-
| [Builder](/creational/builder.md) | Builds a complex object using simple objects | |
19+
| [Builder](/creational/builder.md) | Builds a complex object using simple objects | |
2020
| [Factory Method](/creational/factory.md) | Defers instantiation of an object to a specialized function for creating instances ||
2121
| [Object Pool](/creational/object-pool.md) | Instantiates and maintains a group of objects instances of the same type ||
2222
| [Singleton](/creational/singleton.md) | Restricts instantiation of a type to one object ||

‎creational/builder.md

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# Builder Pattern
2+
3+
Builder pattern separates the construction of a complex object from its
4+
representation so that the same construction process can create different
5+
representations.
6+
7+
In Go, normally a configuration struct is used to achieve the same behavior,
8+
however passing a struct to the builder method fills the code with boilerplate
9+
`if cfg.Field != nil {...}` checks.
10+
11+
## Implementation
12+
13+
```go
14+
package car
15+
16+
type Speed float64
17+
18+
const (
19+
MPH Speed = 1
20+
KPH = 1.60934
21+
)
22+
23+
type Color string
24+
25+
const (
26+
BlueColor Color = "blue"
27+
GreenColor = "green"
28+
RedColor = "red"
29+
)
30+
31+
type Wheels string
32+
33+
const (
34+
SportsWheels Wheels = "sports"
35+
SteelWheels = "steel"
36+
)
37+
38+
type Builder interface {
39+
Color(Color) Builder
40+
Wheels(Wheels) Builder
41+
TopSpeed(Speed) Builder
42+
Build() Interface
43+
}
44+
45+
type Interface interface {
46+
Drive() error
47+
Stop() error
48+
}
49+
```
50+
51+
## Usage
52+
53+
```go
54+
assembly := car.NewBuilder().Paint(car.RedColor)
55+
56+
familyCar := assembly.Wheels(car.SportsWheels).TopSpeed(50 * car.MPH).Build()
57+
familyCar.Drive()
58+
59+
sportsCar := assembly.Wheels(car.SteelWheels).TopSpeed(150 * car.MPH).Build()
60+
sportsCar.Drive()
61+
```

0 commit comments

Comments
 (0)
Please sign in to comment.