go 示例

最后更新于:2022-04-02 04:19:12

[TOC] ## 示例 ### 房屋构建 我们可以看到`igloo­Builder`冰屋生成器与`normal­Builder`普通房屋生成器可建造不同类型房屋
main.go ``` package main import "fmt" // 生成器接口 type iBuilder interface { setWindowType() setDoorType() setNumFloor() // 需要有一个返回构造结果函数 getHouse() house } func getBuilder(builderType string) iBuilder { if builderType == "normal" { return &normalBuilder{} } if builderType == "igloo" { return &iglooBuilder{} } return nil } // 具体生成器 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, } } // 具体生成器 type iglooBuilder struct { windowType string doorType string floor int } func newIglooBuilder() *iglooBuilder { return &iglooBuilder{} } func (b *iglooBuilder) setWindowType() { b.windowType = "Snow Window" } func (b *iglooBuilder) setDoorType() { b.doorType = "Snow Door" } func (b *iglooBuilder) setNumFloor() { b.floor = 1 } func (b *iglooBuilder) getHouse() house { return house{ doorType: b.doorType, windowType: b.windowType, floor: b.floor, } } // 产品 type house struct { windowType string doorType string floor int } // 主管 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() } // 客户端代码 func main() { normalBuilder := getBuilder("normal") 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) iglooBuilder := getBuilder("igloo") director.setBuilder(iglooBuilder) iglooHouse := director.buildHouse() fmt.Printf("\nIgloo House Door Type: %s\n", iglooHouse.doorType) fmt.Printf("Igloo House Window Type: %s\n", iglooHouse.windowType) fmt.Printf("Igloo House Num Floor: %d\n", iglooHouse.floor) } ```

输出 ``` Normal House Door Type: Wooden Door Normal House Window Type: Wooden Window Normal House Num Floor: 2 ```
';