設計模式go語言實現----構建者模式Builder
阿新 • • 發佈:2018-12-17
1 概念
構建者模式定義:
將一個複雜物件的構建與它的表示分離,使得同樣的構建過程可以建立不同的表示
構建者模式包含如下角色:
- Product:具體產品
- ConcreteBuilder:具體建造者
- Builder:抽象建造者
- Director:指揮者
讀者可以對比以下構建者類圖理解各種角色的作用
其中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類圖理解