建造者模式(Builder Pattern)使用多个简单的对象一步一步构建成一个复杂的对象。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
一个 Builder 类会一步一步构造最终的对象。该 Builder 类是独立于其他对象的。
代码实现
package builder //Builder 是生成器接口 type Builder interface { Part1() Part2() Part3() } type Director struct { builder Builder } // NewDirector ... func NewDirector(builder Builder) *Director { return &Director{ builder: builder, } } //Construct Product func (d *Director) Construct() { d.builder.Part1() d.builder.Part2() d.builder.Part3() } type Builder1 struct { result string } func (b *Builder1) Part1() { b.result += "1" } func (b *Builder1) Part2() { b.result += "2" } func (b *Builder1) Part3() { b.result += "3" } func (b *Builder1) GetResult() string { return b.result } type Builder2 struct { result int } func (b *Builder2) Part1() { b.result += 1 } func (b *Builder2) Part2() { b.result += 2 } func (b *Builder2) Part3() { b.result += 3 } func (b *Builder2) GetResult() int { return b.result }
单元测试
package builder import "testing" func TestBuilder1(t *testing.T) { builder := &Builder1{} director := NewDirector(builder) director.Construct() res := builder.GetResult() if res != "123" { t.Fatalf("Builder1 fail expect 123 acture %s", res) } } func TestBuilder2(t *testing.T) { builder := &Builder2{} director := NewDirector(builder) director.Construct() res := builder.GetResult() if res != 6 { t.Fatalf("Builder2 fail expect 6 acture %d", res) } }