Golang设计模式——04建造者模式

建造者模式

定义

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

优点

  1. 建造者模式的封装性很好。使用建造者模式可以有效的封装变化,在使用建造者模式的场景中,一般产品类和建造者类是比较稳定的,因此,将主要的业务逻辑封装在导演类中对整体而言可以取得比较好的稳定性。
  2. 建造者模式很容易进行扩展。如果有新的需求,通过实现一个新的建造者类就可以完成,基本上不用修改之前已经测试通过的代码,因此也就不会对原有功能引入风险。
  3. 在建造者模式中,客户端不必知道产品内部组成的细节,将产品本身与产品的创建过程解耦,使得相同的创建过程可以创建不同的产品对象。
  4. 其次,建造者模式很容易进行扩展。如果有新的需求,通过实现一个新的建造者类就可以完成,基本上不用修改之前已经测试通过的代码,因此也就不会对原有功能引入风险。符合开闭原则。
  5. 由于具体的建造者是独立的,因此可以对建造过程逐步细化,而不对其他模块产生任何影响。

缺点

  1. 建造者模式所创建的产品一般具有较多的共同点,其组成部分相似,如果产品之间的差异性很大,则不适合使用建造者模式,因此其使用范围受到一定的限制。

场景

  1. 需要生产的产品对象有复杂的内部结构。
  2. 需要生产的产品对象的属性相互依赖,建造者模式可以强迫生成顺序。
  3. 在对象创建过程中会使用到系统中的一些其它对象,这些对象在产品对象的创建过程中不易得到。

代码

在这里插入图片描述

package Builder

import "fmt"

type Product struct {
	parts []string
}

func (p *Product) AddParts(s string) {
	p.parts = append(p.parts, s)
}
func (p *Product) ShowParts() {
	fmt.Println(p.parts)
}

type Builder interface {
	BuildPartA()
	BuildPartB()
	BuildPartC()
	GetResult() Product
}
type ConcreteBuilder1 struct {
	product Product
}

func (c *ConcreteBuilder1) BuildPartA() {
	c.product.AddParts("人的头")
}

func (c *ConcreteBuilder1) BuildPartB() {
	c.product.AddParts("两只手")
}

func (c *ConcreteBuilder1) BuildPartC() {
	c.product.AddParts("两条腿")
}

func (c *ConcreteBuilder1) GetResult() Product {
	return c.product
}

type ConcreteBuilder2 struct {
	product Product
}

func (c *ConcreteBuilder2) BuildPartA() {
	c.product.AddParts("狗的头")
}

func (c *ConcreteBuilder2) BuildPartB() {
	c.product.AddParts("狗的爪子")
}

func (c *ConcreteBuilder2) BuildPartC() {
	c.product.AddParts("狗的腿")

}

func (c *ConcreteBuilder2) GetResult() Product {
	return c.product
}

type Director struct {
}

func (d *Director) Construct(builder Builder) {
	builder.BuildPartA()
	builder.BuildPartB()
	builder.BuildPartC()
}

package Builder

import (
	"testing"
)

func TestDirector_Construct(t *testing.T) {
	b1 := &ConcreteBuilder1{product: Product{parts: make([]string, 0)}}
	b2 := &ConcreteBuilder2{product: Product{parts: make([]string, 0)}}
	director := &Director{}
	director.Construct(b1)
	director.Construct(b2)
	p1 := b1.GetResult()
	p2 := b2.GetResult()
	p1.ShowParts()
	p2.ShowParts()
}

其他设计模式

设计模式Git源代码
00简单工厂模式
01工厂方法模式
02抽象工厂模式
03外观模式
04建造者模式
05桥接模式
06命令模式
07迭代器模式
08模板模式
09访问者模式
10备忘录模式
11责任链模式
12中介模式
13原型模式
14状态模式
15策略模式
16享元模式
17组合模式
18解释器模式
19单例模式
20适配器模式
21代理模式
22装饰器模式
23观察者模式

posted @ 2021-09-24 16:56  cheems~  阅读(59)  评论(0编辑  收藏  举报