Go言語入門 / golang 入門デザインパターン Builder

f:id:nasust:20161122141513p:plain The Go gopher was designed by Renee French. (http://reneefrench.blogspot.com/) CC3.0

こんにちはnasustです。 前回はデザインパターンAbstractFactoryをGo言語/ golangでの実装を解説しました。 今回も、オブジェクト指向デザインパターンをGo言語 / golangでどうやって実現する解説したいと思います。

Builderの実装

Builder パターン - Wikipedia

Wikipediaの解説を元にGo言語 / golangでプログラミングしてみます。

package main

import "fmt"

type Material int

const (
    Wood Material = iota
    Clay
    Concrete
    Snow
)

func (i Material) String() string {
    switch i {
    case Wood:
        return "Wood"
    case Clay:
        return "Clay"
    case Concrete:
        return "Concrete"
    case Snow:
        return "Snow"
    }
    return "Unknown"
}

type Building struct {
    base  Material
    frame Material
    wall  Material
}

func (building *Building) String() string {
    return "[Base:" + building.base.String() + ", Frame:" + building.frame.String() + ", Wall:" + building.wall.String()
}

type Builder interface {
    BuildBase()
    BuildFrame()
    BuildWall()
    GetResult() *Building
}

type JapaneseHouseBuilder struct {
    building *Building
}

func (builder *JapaneseHouseBuilder) BuildBase() {
    builder.building.base = Concrete
}

func (builder *JapaneseHouseBuilder) BuildFrame() {
    builder.building.frame = Wood
}

func (builder *JapaneseHouseBuilder) BuildWall() {
    builder.building.wall = Clay
}

func (builder *JapaneseHouseBuilder) GetResult() *Building {
    return builder.building
}

func NewJapaneseHouseBuilder() *JapaneseHouseBuilder {
    return &JapaneseHouseBuilder{new(Building)}
}

type KamakuraHouseBuilder struct {
    building *Building
}

func (builder *KamakuraHouseBuilder) BuildBase() {
    builder.building.base = Snow
}

func (builder *KamakuraHouseBuilder) BuildFrame() {
    builder.building.frame = Snow
}

func (builder *KamakuraHouseBuilder) BuildWall() {
    builder.building.wall = Snow
}

func (builder *KamakuraHouseBuilder) GetResult() *Building {
    return builder.building
}

func NewKamakuraHouseBuilder() *KamakuraHouseBuilder {
    return &KamakuraHouseBuilder{new(Building)}
}

type Director struct {
    Builder Builder
}

func (director *Director) Constract() *Building {
    director.Builder.BuildBase()
    director.Builder.BuildFrame()
    director.Builder.BuildWall()
    return director.Builder.GetResult()
}

func NewDirector(builder Builder) *Director {
    return &Director{builder}
}

func main() {
    d1 := NewDirector(NewJapaneseHouseBuilder())
    d2 := NewDirector(NewKamakuraHouseBuilder())
    b1 := d1.Constract()
    b2 := d2.Constract()
    fmt.Println(b1)
    fmt.Println(b2)
}

実行すると下記のように表示されます。

[Base:Concrete, Frame:Wood, Wall:Clay
[Base:Snow, Frame:Snow, Wall:Snow

BuilderパターンもGo言語 / golangで問題なく実装できますね。


Go言語 / golang 入門 目次に戻る

広告を非表示にする