Modo de construcción (constructor)
1. Intención
Separar la estructura de un objeto complejo de su representación permite que el mismo proceso de construcción cree diferentes representaciones.
2. Aplicabilidad
Utilice el modo Constructor en las siguientes situaciones
- Cuando el algoritmo para crear objetos complejos debe ser independiente de los componentes del objeto y cómo se ensamblan.
- Cuando el proceso de construcción debe permitir diferentes representaciones de los objetos que se están construyendo.
3. Estructura
4. Código
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)
}