建造模式(Builder)

建造模式(Builder)

1.意图

将一个复杂对象的结构与它的表示分离,使得同样的构建过程可以创建不同的表示。

2.适用性

在以下情况使用Builder模式

  • 当创建复杂对象的算法应该独立于该对象的组成部分以及它们的装配方式时。
  • 当构造过程必须允许被构造的对象有不同的表示时。

3.结构

在这里插入图片描述

4.代码

package builder


import "testing"


//Builder 是生成器接口
type Builder interface {
    
    
	BuildA()
	BuildB()
	BuildC()
}


type Director struct {
    
     //指挥者
	builder Builder
}


// NewDirector ...
func NewDirector(builder Builder) *Director {
    
    
	return &Director{
    
    
		builder: builder,
	}
}


//Construct Product
func (d *Director) Construct() {
    
    
	d.builder.BuildA()
	d.builder.BuildB()
	d.builder.BuildC()
}



type Builder1 struct {
    
    
	result string
}


func (b *Builder1) BuildA() {
    
    
	b.result += "一"
}


func (b *Builder1) BuildB() {
    
    
	b.result += "二"
}


func (b *Builder1) BuildC() {
    
    
	b.result += "三"
}

func (b *Builder1) GetResult() string {
    
    
	return b.result
}


type Builder2 struct {
    
    
	result int
}


func (b *Builder2) BuildA() {
    
    
	b.result += 1
}


func (b *Builder2) BuildB() {
    
    
	b.result += 2
}


func (b *Builder2) BuildC() {
    
    
	b.result += 3
}


func (b *Builder2) GetResult() int {
    
    
	return b.result
}


func TestBuilder1(t *testing.T) {
    
    
	builder := &Builder1{
    
    }
	director := NewDirector(builder)
	director.Construct()
	res := builder.GetResult()
	if res != "一二三" {
    
    
		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)
	}
}




type Person struct {
    
    
	name string
	sex  int
	age  int
}

type BuildPerson interface {
    
    
	WithName(name string) Person
	WithSex(sex int) Person
	WithAge(age int) Person
}

func (this *Person)WithName(name string)*Person{
    
    
	this.name=name
	return this
}
func (this *Person)WithSex(sex int)*Person{
    
    
	this.sex=sex
	return this
}

func (this *Person)WithAge(age int)*Person{
    
    
	this.age=age
	return this
}

func TestPersonCreator(t *testing.T){
    
    
	p:=&Person{
    
    }
	p.WithAge(1).WithName("小明").WithAge(12)

	t.Log(p)
}

猜你喜欢

转载自blog.csdn.net/dawnto/article/details/112973474
今日推荐