生成器模式建议将对象构造代码从产品类中抽取出来, 并将其放在一个名为生成器的独立对象中。
使用建造普通房子以及别墅来模拟
iBuilder.go: 生成器接口
package main
type IBuilder interface {
setWindowType()
setDoorType()
setNumFloor()
getHouse() House
}
func getBuilder(builderType string) IBuilder {
if builderType == "normal" {
return newNormalBuilder()
}
if builderType == "villa" {
return newVillaBuilder()
}
return nil
}
normalBuilder.go: 普通房子生成器
package main
type NormalBuilder struct {
windowType string
doorType string
floor int
}
func newNormalBuilder() *NormalBuilder {
return &NormalBuilder{}
}
func (b *NormalBuilder) setWindowType() {
b.windowType = "Wooden Window"
}
func (b *NormalBuilder) setDoorType() {
b.doorType = "Wooden Door"
}
func (b *NormalBuilder) setNumFloor() {
b.floor = 2
}
func (b *NormalBuilder) getHouse() House {
return House{
doorType: b.doorType,
windowType: b.windowType,
floor: b.floor,
}
}
villaBuilder.go: 别墅生成器
package main
type VillaBuilder struct {
windowType string
doorType string
floor int
}
func newVillaBuilder() *VillaBuilder {
return &VillaBuilder{}
}
func (b *VillaBuilder) setWindowType() {
b.windowType = "Snow Window"
}
func (b *VillaBuilder) setDoorType() {
b.doorType = "Snow Door"
}
func (b *VillaBuilder) setNumFloor() {
b.floor = 1
}
func (b *VillaBuilder) getHouse() House {
return House{
doorType: b.doorType,
windowType: b.windowType,
floor: b.floor,
}
}
house.go: 房子产品
package main
type House struct {
windowType string
doorType string
floor int
}
director.go: 主管类
package main
type Director struct {
builder IBuilder
}
func newDirector(b IBuilder) *Director {
return &Director{
builder: b,
}
}
func (d *Director) setBuilder(b IBuilder) {
d.builder = b
}
func (d *Director) buildHouse() House {
d.builder.setDoorType()
d.builder.setWindowType()
d.builder.setNumFloor()
return d.builder.getHouse()
}
main.go: 客户端
package main
import "fmt"
func main() {
normalBuilder := getBuilder("normal")
villaBuilder := getBuilder("villa")
director := newDirector(normalBuilder)
normalHouse := director.buildHouse()
fmt.Printf("Normal House Door Type: %s\n", normalHouse.doorType)
fmt.Printf("Normal House Window Type: %s\n", normalHouse.windowType)
fmt.Printf("Normal House Num Floor: %d\n", normalHouse.floor)
director.setBuilder(villaBuilder)
villa := director.buildHouse()
fmt.Printf("\nIgloo House Door Type: %s\n", villa.doorType)
fmt.Printf("Igloo House Window Type: %s\n", villa.windowType)
fmt.Printf("Igloo House Num Floor: %d\n", villa.floor)
}
output:
Normal House Door Type: Wooden Door
Normal House Window Type: Wooden Window
Normal House Num Floor: 2
Igloo House Door Type: Snow Door
Igloo House Window Type: Snow Window
Igloo House Num Floor: 1