Go 设计模式--Builder模式

造者模式(Builder Pattern):将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

建造者模式是一步一步创建一个复杂的对象,它允许用户只通过指定复杂对象的类型和内容就可以构建它们,用户不需要知道内部的具体构建细节。建造者模式属于对象创建型模式。根据中文翻译的不同,建造者模式又可以称为生成器模式。

package builder

import(
	"fmt"
)


type Builder interface {
	Step1()
	Step2()
	Step3()
} 

type Xiaomi struct{
	Function string
}

func (this *Xiaomi)Step1(){
	fmt.Println("小米Step1")
	this.Function += "[打电话]"
}
func (this *Xiaomi)Step2(){
	fmt.Println("小米Step2")
	this.Function += "[游戏]"
}
func (this *Xiaomi)Step3(){
	fmt.Println("小米Step3")
	this.Function += "[便宜]"
}
func (this *Xiaomi)GetFunction()string{
	fmt.Println( this.Function)
	return this.Function
}

type Huawei struct{
	Function string
}

func (this *Huawei)Step1(){
	fmt.Println("华为Step1")
	this.Function += "[打电话]"
}
func (this *Huawei)Step2(){
	fmt.Println("华为Step2")
	this.Function += "[拍照]"
}
func (this *Huawei)Step3(){
	fmt.Println("华为Step3")
	this.Function += "[贵]"
}
func (this *Huawei)GetFunction()string{
	fmt.Println( this.Function)
	return this.Function
}


type Drictor struct{
	bui Builder
}

func NewConstruct(bui Builder)*Drictor{
	return &Drictor{
		bui : bui,
	}
}

func(this *Drictor)Consturct(){
	this.bui.Step1()
	this.bui.Step2()
	this.bui.Step3()
}

  

	xm := builder.Xiaomi{}
	drictor:= builder.NewConstruct(&xm)
	drictor.Consturct()
	xm.GetFunction()

	hw := builder.Huawei{}
	drictor2 := builder.NewConstruct(&hw)
	drictor2.Consturct()
	hw.GetFunction()

  

 不同的建造者同样的步骤最终创建的结果不一样

猜你喜欢

转载自www.cnblogs.com/flycc/p/12628434.html
今日推荐