1
0
Fork 0
design-patterns/go/builder/main.go

121 lines
2.5 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import "fmt"
/* 实例
汤宝宝想要建造一栋属于自己的房子,于是找来了著名的建筑设计
公司——生成者模式公司Builder Pattern Inc.)帮忙设计和建造房子。
*/
// 产品:房子
type House struct {
Foundation string // 地基
Structure string // 结构
Roof string // 屋顶
}
// 建造者接口
type HouseBuilder interface {
buildFoundation()
buildStructure()
buildRoof()
getHouse() House
}
// 具体建造者:木屋建造者
type WoodenHouseBuilder struct {
house House
}
func (b *WoodenHouseBuilder) buildFoundation() {
b.house.Foundation = "木桩地基"
fmt.Println(" 建造木桩地基")
}
func (b *WoodenHouseBuilder) buildStructure() {
b.house.Structure = "木结构"
fmt.Println(" 建造木结构")
}
func (b *WoodenHouseBuilder) buildRoof() {
b.house.Roof = "木屋顶"
fmt.Println(" 建造木屋顶")
}
func (b *WoodenHouseBuilder) getHouse() House {
return b.house
}
// 具体建造者:砖房建造者
type BrickHouseBuilder struct {
house House
}
func (b *BrickHouseBuilder) buildFoundation() {
b.house.Foundation = "混凝土地基"
fmt.Println(" 建造混凝土地基")
}
func (b *BrickHouseBuilder) buildStructure() {
b.house.Structure = "砖结构"
fmt.Println(" 建造砖结构")
}
func (b *BrickHouseBuilder) buildRoof() {
b.house.Roof = "瓦屋顶"
fmt.Println(" 建造瓦屋顶")
}
func (b *BrickHouseBuilder) getHouse() House {
return b.house
}
// 指挥者
type Director struct {
builder HouseBuilder
house House
}
// 重置房子
func (d *Director) reset() {
d.house = House{}
}
func (d *Director) setBuilder(b HouseBuilder) {
d.builder = b
}
func (d *Director) constructHouse() {
d.reset()
d.builder.buildFoundation()
d.builder.buildStructure()
d.builder.buildRoof()
d.house = d.builder.getHouse()
}
func main() {
var builder HouseBuilder
var director Director
var house House
fmt.Println("========= 生成者模式 =========")
// 使用木屋建造者
builder = &WoodenHouseBuilder{}
director.setBuilder(builder)
fmt.Println("建造木屋:")
director.constructHouse()
house = director.house
fmt.Printf("木屋建造完成:%s %s %s\n\n", house.Foundation, house.Structure, house.Roof)
// 使用砖房建造者
builder = &BrickHouseBuilder{}
director.setBuilder(builder)
fmt.Println("建造砖房:")
director.constructHouse()
house = director.house
fmt.Printf("砖房建造完成:%s %s %s\n\n", house.Foundation, house.Structure, house.Roof)
fmt.Println("======= 生成者模式结束 =======")
}