From e7af050223428de27620d68d5d6217e7568f5434 Mon Sep 17 00:00:00 2001 From: Tamer Tas Date: Wed, 22 Feb 2017 18:02:38 +0300 Subject: [PATCH] creational/builder: implement the builder pattern --- README.md | 2 +- creational/builder.md | 61 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 creational/builder.md diff --git a/README.md b/README.md index c9fa11e..cfc72b8 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ A curated collection of idiomatic design & application patterns for Go language. | Pattern | Description | Status | |:-------:|:----------- |:------:| | [Abstract Factory](/creational/abstract_factory.md) | Provides an interface for creating families of releated objects | ✘ | -| [Builder](/creational/builder.md) | Builds a complex object using simple objects | ✘ | +| [Builder](/creational/builder.md) | Builds a complex object using simple objects | ✔ | | [Factory Method](/creational/factory.md) | Defers instantiation of an object to a specialized function for creating instances | ✔ | | [Object Pool](/creational/object-pool.md) | Instantiates and maintains a group of objects instances of the same type | ✔ | | [Singleton](/creational/singleton.md) | Restricts instantiation of a type to one object | ✔ | diff --git a/creational/builder.md b/creational/builder.md new file mode 100644 index 0000000..e19179e --- /dev/null +++ b/creational/builder.md @@ -0,0 +1,61 @@ +# Builder Pattern + +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. + +## Implementation + +```go +package 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 +} +``` + +## Usage + +```go +assembly := 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() +```