建造者模式将一个复杂的对象与它的表示分离,同样的创造过程可以建造出不同的表示。

一、定义产品—–要建造什么?
type Car struct {
Brand string
Type string
Color string
}
func (this *Car) Drive() error {
fmt.Printf(“A %s %s %s car is running on the road!\n”, this.Color, this.Type, this.Brand)
return nil
}
二、定义建造者—用什么方式方法建造?
//建造者角色
type Builder interface {
PaintColor(color string) Builder
AddBrand(brand string) Builder
SetType(t string) Builder
Build() Car
}
//具体的建造者
type ConcreteBuilder struct {
ACar Car
}
func (this *ConcreteBuilder) PaintColor(cor string) Builder {
this.ACar.Color = cor
return this
}
func (this *ConcreteBuilder) AddBrand(bnd string) Builder {
this.ACar.Brand = bnd
return this
}
func (this *ConcreteBuilder) SetType(t string) Builder {
this.ACar.Type = t
return this
}
func (this *ConcreteBuilder) Build() Car {
return this.ACar
}
三、定义建造者实施—输出成品!
type Director struct {
Builder Builder
}
示例:
dr := Director{&ConcreteBuilder{}}
adCar := dr.Builder.SetType(“SUV”).AddBrand(” 奥迪 “).PaintColor(“white”).Build()
adCar.Drive()
bwCar := dr.Builder.SetType(“sporting”).AddBrand(“宝马”).PaintColor(“red”).Build()
bwCar.Drive()
小结:建造者模式经常用在创建连接,构建实例时,开发中经常用到,绝对五颗星。
更多内容请关注每日编程,每天进步一点。