Golang设计模式之构造者模式

Jackey Golang 2,148 次浏览 , , 没有评论

创建文件:Builder.go

package Builder

type Builder interface {
    Part1()
    Part2()
    Part3()
}

type Director struct {
    builder Builder // 建造者的接口
}

// 创造一个接口
func NewDirector(builder Builder) *Director {
    return &Director{builder: builder}
}

func (d *Director) MakeData() {
    d.builder.Part1()
    d.builder.Part2()
    d.builder.Part3()
}

创建文件:IntBuilder.go

package Builder

type IntBuilder struct {
    Result int64
}

func (sb *IntBuilder) Part1() {
    sb.Result += 1
}

func (sb *IntBuilder) Part2() {
    sb.Result += 2
}

func (sb *IntBuilder) Part3() {
    sb.Result += 3
}

func (sb *IntBuilder) GetResult() int64 {
    return sb.Result
}

创建文件:StringBuilder.go

package Builder

type StringBuilder struct {
    Result string
}

func (sb *StringBuilder) Part1() {
    sb.Result += "1"
}

func (sb *StringBuilder) Part2() {
    sb.Result += "2"
}

func (sb *StringBuilder) Part3() {
    sb.Result += "3"
}

func (sb *StringBuilder) GetResult() string {
    return sb.Result
}

main.go

package main

import (
    "fmt"
    "test/design/Builder"
)

func main() {
    //builder := &Builder.StringBuilder{}
    builder := &Builder.IntBuilder{}
    dict := Builder.NewDirector(builder)
    dict.MakeData()
    fmt.Println(builder.GetResult())
}

 

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

Go