add builder pattern

This commit is contained in:
Edward 2020-04-27 12:29:44 +08:00
parent 672e565428
commit 6c5ef1324a
3 changed files with 47 additions and 46 deletions

View File

@ -0,0 +1,4 @@
# 创建者模式
重点分块创造,返回创建者接口
演示一个造车的例子

View File

@ -1,66 +1,63 @@
package builder package builder
//Builder 是生成器接口 //ICar 汽车,我们要造车了
type Builder interface { //ICar 车具有以下能力
Part1() type ICar interface {
Part2() Start()
Part3() Stop()
Speed() int
Brand() string
} }
type Director struct { //ICarBuilder 用来造车
builder Builder type ICarBuilder interface {
Wheel(wheel int) ICarBuilder
Engine(engine string) ICarBuilder
Speed(max int) ICarBuilder
Brand(brand string) ICarBuilder
Build() ICar
} }
// NewDirector ... //CarProto 车的原型
func NewDirector(builder Builder) *Director { type CarProto struct {
return &Director{ Wheel int
builder: builder, Engine string
} MaxSpeed int
Brand string
} }
//Construct Product //CarStudio 打算通过成立造车实验室进行造车
func (d *Director) Construct() { type CarStudio struct {
d.builder.Part1() prototype CarProto
d.builder.Part2()
d.builder.Part3()
} }
type Builder1 struct { // NewCarStudio 造车工作室
result string func NewCarStudio() ICarBuilder {
return &CarStudio{}
} }
func (b *Builder1) Part1() { // Wheel of car
b.result += "1" func (c *CarStudio) Wheel(wheel int) ICarBuilder {
c.prototype.Wheel = wheel
return c
} }
func (b *Builder1) Part2() { // Engine of car
b.result += "2" func (c *CarStudio) Engine(engine string) ICarBuilder {
return c
} }
func (b *Builder1) Part3() { // Speed of car
b.result += "3" func (c *CarStudio) Speed(max int) ICarBuilder {
return c
} }
func (b *Builder1) GetResult() string { // Brand of car
return b.result func (c *CarStudio) Brand(brand string) ICarBuilder {
return c
} }
type Builder2 struct { // Build return a car
result int func (c *CarStudio) Build() ICar {
} return c.prototype
func (b *Builder2) Part1() {
b.result += 1
}
func (b *Builder2) Part2() {
b.result += 2
}
func (b *Builder2) Part3() {
b.result += 3
}
func (b *Builder2) GetResult() int {
return b.result
} }

View File

@ -1,3 +1,3 @@
# creation pattern # creation pattern
创建模式,用于创建对象 创建模式,用于创建对象