建造者模式

建造者模式将复杂对象的构造与其表示形式分开,以便同一构造过程可以创建不同的表示形式。

一个建造者会各种技能,由一个指挥者指挥来完成这一构建过程:画一个人举例,一个人有头、身体、胳膊、腿、脚,对于建造者来说,它能够画出各个部分,又指挥者规范绘制过程。

package DesignPatterns

import "fmt"

// 建造者
type PersonBuilder interface {
    BuildHead()
    BuildBody()
    BuildArm()
    BuildLeg()
    BuildFoot()
}

// 指挥者(控制建造顺序)
type PersonDirector interface {
    SetBuilder(PersonBuilder)
    BuildPerson()
}

type Director struct {
    builder PersonBuilder
}

func (d *Director) SetBuilder(b PersonBuilder) {
    d.builder = b
}
func (d *Director) BuildPerson() {
    d.builder.BuildHead()
    d.builder.BuildBody()
    d.builder.BuildArm()
    d.builder.BuildLeg()
    d.builder.BuildFoot()
}

func NewDirector() PersonDirector {
    return &Director{}
}

// 建造师A
type BuilderA struct{}

func (b *BuilderA) BuildHead() {
    fmt.Println("head A")
}
func (b *BuilderA) BuildBody() {
    fmt.Println("body A")
}
func (b *BuilderA) BuildArm() {
    fmt.Println("arm A")
}
func (b *BuilderA) BuildLeg() {
    fmt.Println("leg A")
}
func (b *BuilderA) BuildFoot() {
    fmt.Println("foot A")
}

// 建造师B
type BuilderB struct{}

func (b *BuilderB) BuildHead() {
    fmt.Println("head B")
}
func (b *BuilderB) BuildBody() {
    fmt.Println("body B")
}
func (b *BuilderB) BuildArm() {
    fmt.Println("arm B")
}
func (b *BuilderB) BuildLeg() {
    fmt.Println("leg B")
}
func (b *BuilderB) BuildFoot() {
    fmt.Println("foot B")
}

// 简单工厂
func NewBuilder(t string) PersonBuilder {
    switch t {
    case "A":
    	return &BuilderA{}
    case "B":
    	return &BuilderB{}
    }
    return &BuilderA{}
}

  • 使用
func TestNewDirector(t *testing.T) {
    director := NewDirector()
    director.SetBuilder(NewBuilder("A"))
    director.BuildPerson()

    director.SetBuilder(NewBuilder("B"))
    director.BuildPerson()
}