设计模式go语言实现----构建者模式Builder

1 概念

构建者模式定义:

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

构建者模式包含如下角色:

  • Product:具体产品
  • ConcreteBuilder:具体建造者
  • Builder:抽象建造者
  • Director:指挥者

读者可以对比以下构建者类图理解各种角色的作用

设计模式go语言实现----构建者模式Builder_第1张图片其中ActorController充当指挥者(Director),ActorBuilder充当抽象建造者,HeroBuilder、AngelBuilder充当具体建造者,Actor充当复杂产品。其中ActorController充当指挥者(Director),ActorBuilder充当抽象建造者,HeroBuilder、AngelBuilder和DevilBuilder充当具体建造者,Actor充当复杂产品。

2 go语言实现

2.1 定义产品角色

type Actor struct {
	Type      string
	Sex       string
	Face      string
	Costume   string
	HairStyle string
}

func (a Actor) ShowActorInfo() {
	fmt.Println("角色类型: ", a.Type)
	fmt.Println("角色性别: ", a.Sex)
	fmt.Println("角色面容: ", a.Face)
	fmt.Println("角色服装: ", a.Costume)
	fmt.Println("角色发型: ", a.HairStyle)
}

2.2 定义抽象建造者角色

type ActorBuilder interface {
	BuildType()
	BuildSex()
	BuildFace()
	BuildCostume()
	BuildHairStyle()
	CreateActor() Actor
}

2.3 定义具体建造者角色

type HeroBuilder struct {
	actor Actor
}

func (hb *HeroBuilder) BuildType() {
	hb.actor.Type = "英雄"
}

func (hb *HeroBuilder) BuildSex() {
	hb.actor.Sex = "男"
}

func (hb *HeroBuilder) BuildFace() {
	hb.actor.Face = "英俊"
}

func (hb *HeroBuilder) BuildCostume() {
	hb.actor.Costume = "盔甲"
}

func (hb *HeroBuilder) BuildHairStyle() {
	hb.actor.HairStyle = "飘逸"
}

func (hb HeroBuilder) CreateActor() Actor {
	return hb.actor
}

type AngelBuilder struct {
	actor Actor
}

func (ab *AngelBuilder) BuildType() {
	ab.actor.Type = "天使"
}

func (ab *AngelBuilder) BuildSex() {
	ab.actor.Sex = "女"
}

func (ab *AngelBuilder) BuildFace() {
	ab.actor.Face = "漂亮"
}

func (ab *AngelBuilder) BuildCostume() {
	ab.actor.Costume = "白裙"
}

func (ab *AngelBuilder) BuildHairStyle() {
	ab.actor.HairStyle = "披肩长发"
}

func (ab AngelBuilder) CreateActor() Actor {
	return ab.actor
}

2.4 定义指挥者角色

type ActorController struct {
	actorBuilder ActorBuilder
}

func (ac *ActorController) Construct() Actor {
	ac.actorBuilder.BuildType()
	ac.actorBuilder.BuildFace()
	ac.actorBuilder.BuildCostume()
	ac.actorBuilder.BuildSex()
	ac.actorBuilder.BuildHairStyle()
	return ac.actorBuilder.CreateActor()
}

由于go中没有析构函数,使用New方法创建一个指挥者

    func NewActorController(ab ActorBuilder) *ActorController {
    	return &ActorController{
    		actorBuilder: ab,
    	}
    }

2.5 demo调用

package main

import (
	"design_pattern/builder"
	"fmt"
)

func main() {
	var tActor builder.Actor
	tHeroBuilder := builder.HeroBuilder{}
	tAngelBuilder := builder.AngelBuilder{}

	tActorController := builder.NewActorController(&tHeroBuilder)
	tActor = tActorController.Construct()
	tActor.ShowActorInfo()

	fmt.Println("========================")

	tActorController = builder.NewActorController(&tAngelBuilder)
	tActor = tActorController.Construct()
	tActor.ShowActorInfo()
}

读者可以结合代码对照前面的UML类图理解

你可能感兴趣的:(设计模式,go,设计模式之go语言实现)