File tree Expand file tree Collapse file tree 2 files changed +62
-1
lines changed Expand file tree Collapse file tree 2 files changed +62
-1
lines changed Original file line number Diff line number Diff 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 | ✔ |
Original file line number Diff line number Diff line change 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+ ```
You can’t perform that action at this time.
0 commit comments