Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

creational/builder: Added a complete example of the builder pattern #38

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 59 additions & 7 deletions creational/builder.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ however passing a struct to the builder method fills the code with boilerplate
```go
package car

type Speed float64
import "strconv"

type Speed float32

const (
MPH Speed = 1
Expand Down Expand Up @@ -43,8 +45,55 @@ type Builder interface {
}

type Interface interface {
Drive() error
Stop() error
Drive() string
Stop() string
}

type carBuilder struct {
speed Speed
color Color
wheels Wheels
}

type carObject struct {
topSpeed Speed
color Color
wheels Wheels
}

func NewBulder() Builder {
return &carBuilder{}
}

func (cb *carBuilder) TopSpeed(speed Speed) Builder {
cb.speed = speed
return cb
}

func (cb *carBuilder) Paint(color Color) Builder {
cb.color = color
return cb
}

func (cb *carBuilder) Wheels(wheels Wheels) Builder {
cb.wheels = wheels
return cb
}

func (cb *carBuilder) Build() Interface {
return &carObject{
topSpeed: cb.speed,
color: cb.color,
wheels: cb.wheels,
}
}

func (c *carObject) Drive() string {
return "Driving at speed: " + strconv.FormatFloat(float64(c.topSpeed), 'f', 2, 32)
}

func (c *carObject) Stop() string {
return "Stopping a " + string(c.color) + " car"
}
```

Expand All @@ -53,9 +102,12 @@ type Interface interface {
```go
assembly := car.NewBuilder().Paint(car.RedColor)

familyCar := assembly.Wheels(car.SportsWheels).TopSpeed(50 * car.MPH).Build()
familyCar.Drive()
familyCar := assembly.Wheels(car.SteelWheels).TopSpeed(50 * car.MPH).Build()
fmt.Println(familyCar.Drive())

sportsCar := assembly.Paint(car.BlueColor).Wheels(car.SportsWheels).TopSpeed(150 * car.MPH).Build()
fmt.Println(sportsCar.Drive())

sportsCar := assembly.Wheels(car.SteelWheels).TopSpeed(150 * car.MPH).Build()
sportsCar.Drive()
fmt.Println(familyCar.Stop())
fmt.Println(sportsCar.Stop()
```