go-pattern-examples/creation/03_builder/builder.go

94 lines
1.7 KiB
Go
Raw Permalink Normal View History

2020-04-21 17:50:21 +03:00
package builder
2020-04-27 12:17:55 +03:00
import "fmt"
2020-04-27 07:29:44 +03:00
//ICar 汽车,我们要造车了
//ICar 车具有以下能力
type ICar interface {
Speed() int
Brand() string
2020-04-27 12:17:55 +03:00
Brief()
2020-04-21 17:50:21 +03:00
}
2020-04-27 07:49:49 +03:00
//ICarBuilder 造一辆车需要具有的部件
2020-04-27 07:29:44 +03:00
type ICarBuilder interface {
Wheel(wheel int) ICarBuilder
Engine(engine string) ICarBuilder
Speed(max int) ICarBuilder
Brand(brand string) ICarBuilder
Build() ICar
2020-04-21 17:50:21 +03:00
}
2020-04-27 07:29:44 +03:00
//CarProto 车的原型
type CarProto struct {
2020-04-27 07:49:49 +03:00
Wheel int
Engine string
MaxSpeed int
BrandName string
}
//Speed 最大车速
func (c *CarProto) Speed() int {
return c.MaxSpeed
}
//Brand 车品牌
func (c *CarProto) Brand() string {
return c.BrandName
2020-04-21 17:50:21 +03:00
}
2020-04-27 12:17:55 +03:00
//Brief 简介
func (c *CarProto) Brief() {
fmt.Println("this is a cool car")
fmt.Println("car wheel size: ", c.Wheel)
fmt.Println("car MaxSpeed: ", c.MaxSpeed)
fmt.Println("car Engine: ", c.Engine)
}
2020-04-27 07:29:44 +03:00
//CarStudio 打算通过成立造车实验室进行造车
type CarStudio struct {
prototype CarProto
2020-04-21 17:50:21 +03:00
}
2020-04-27 07:29:44 +03:00
// NewCarStudio 造车工作室
func NewCarStudio() ICarBuilder {
return &CarStudio{}
2020-04-21 17:50:21 +03:00
}
2020-04-27 07:29:44 +03:00
// Wheel of car
func (c *CarStudio) Wheel(wheel int) ICarBuilder {
c.prototype.Wheel = wheel
return c
2020-04-21 17:50:21 +03:00
}
2020-04-27 07:29:44 +03:00
// Engine of car
func (c *CarStudio) Engine(engine string) ICarBuilder {
2020-04-27 07:49:49 +03:00
c.prototype.Engine = engine
2020-04-27 07:29:44 +03:00
return c
2020-04-21 17:50:21 +03:00
}
2020-04-27 07:29:44 +03:00
// Speed of car
func (c *CarStudio) Speed(max int) ICarBuilder {
2020-04-27 07:49:49 +03:00
c.prototype.MaxSpeed = max
2020-04-27 07:29:44 +03:00
return c
2020-04-21 17:50:21 +03:00
}
2020-04-27 07:29:44 +03:00
// Brand of car
func (c *CarStudio) Brand(brand string) ICarBuilder {
2020-04-27 07:49:49 +03:00
c.prototype.BrandName = brand
2020-04-27 07:29:44 +03:00
return c
2020-04-21 17:50:21 +03:00
}
2020-04-27 07:29:44 +03:00
// Build return a car
func (c *CarStudio) Build() ICar {
2020-04-27 07:49:49 +03:00
car := &CarProto{
Wheel: c.prototype.Wheel,
Engine: c.prototype.Engine,
MaxSpeed: c.prototype.MaxSpeed,
BrandName: c.prototype.BrandName,
}
return car
2020-04-21 17:50:21 +03:00
}