创建文件:Builder.go
package Builder type Builder interface { Part1() Part2() Part3() } type Director struct { builder Builder // 建造者的接口 } // 创造一个接口 func NewDirector(builder Builder) *Director { return &Director{builder: builder} } func (d *Director) MakeData() { d.builder.Part1() d.builder.Part2() d.builder.Part3() }
创建文件:IntBuilder.go
package Builder type IntBuilder struct { Result int64 } func (sb *IntBuilder) Part1() { sb.Result += 1 } func (sb *IntBuilder) Part2() { sb.Result += 2 } func (sb *IntBuilder) Part3() { sb.Result += 3 } func (sb *IntBuilder) GetResult() int64 { return sb.Result }
创建文件:StringBuilder.go
package Builder type StringBuilder struct { Result string } func (sb *StringBuilder) Part1() { sb.Result += "1" } func (sb *StringBuilder) Part2() { sb.Result += "2" } func (sb *StringBuilder) Part3() { sb.Result += "3" } func (sb *StringBuilder) GetResult() string { return sb.Result }
main.go
package main import ( "fmt" "test/design/Builder" ) func main() { //builder := &Builder.StringBuilder{} builder := &Builder.IntBuilder{} dict := Builder.NewDirector(builder) dict.MakeData() fmt.Println(builder.GetResult()) }