Golang生成器模式

FredricZhu · · 1254 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

builder.go

// builder
package builder

type VehicleProduct struct {
    Wheels    int
    Seats     int
    Structure string
}

type BuildProcess interface {
    SetWheels() BuildProcess
    SetSeats() BuildProcess
    SetStructure() BuildProcess
    GetVehicle() VehicleProduct
}

//MenufacturingDirector Begin
type ManufacturingDiretcor struct {
    builder BuildProcess
}

func (f *ManufacturingDiretcor) Construct() {
    f.builder.SetWheels().SetSeats().SetStructure()
}

func (f *ManufacturingDiretcor) SetBuilder(b BuildProcess) {
    f.builder = b
}

//MenufacturingDirector End

//Car Builder Start implements BuildProcess
type CarBuilder struct {
    v VehicleProduct
}

func (c *CarBuilder) SetWheels() BuildProcess {
    c.v.Wheels = 4
    return c
}

func (c *CarBuilder) SetSeats() BuildProcess {
    c.v.Seats = 5
    return c
}

func (c *CarBuilder) SetStructure() BuildProcess {
    c.v.Structure = "Car"
    return c
}

func (c *CarBuilder) GetVehicle() VehicleProduct {
    return c.v
}

//Car Builder End

//Bike Builder Start implements BuildProcess
type BikeBuilder struct {
    v VehicleProduct
}

func (b *BikeBuilder) SetWheels() BuildProcess {
    b.v.Wheels = 2
    return b
}

func (b *BikeBuilder) SetSeats() BuildProcess {
    b.v.Seats = 2
    return b
}

func (b *BikeBuilder) SetStructure() BuildProcess {
    b.v.Structure = "Motorbike"
    return b
}

func (b *BikeBuilder) GetVehicle() VehicleProduct {
    return b.v
}

//Bike Builder End

builder_test.go

package builder

import (
    "testing"
)

func TestBuilderPattern(t *testing.T) {
    manufactureComplex := ManufacturingDiretcor{}

    carBuilder := &CarBuilder{}
    manufactureComplex.SetBuilder(carBuilder)
    manufactureComplex.Construct()
    car := carBuilder.GetVehicle()

    if car.Wheels != 4 {
        t.Errorf("Wheels on a car must be 4, but it is %d \n", car.Wheels)
    }

    if car.Structure != "Car" {
        t.Errorf("Structure Of a car must be 'Car', but it is %v \n", car.Structure)
    }

    if car.Seats != 5 {
        t.Errorf("Seats on a car must be 5, but it is %d \n", car.Seats)
    }

    bikeBuilder := &BikeBuilder{}
    manufactureComplex.SetBuilder(bikeBuilder)
    manufactureComplex.Construct()
    motoBike := bikeBuilder.GetVehicle()

    motoBike.Seats = 1
    if motoBike.Wheels != 2 {
        t.Errorf("Wheels on a motobike must be 2 but found %d \n", motoBike.Wheels)
    }

    if motoBike.Structure != "Motorbike" {
        t.Errorf("Structure of a motobike must be 'Motorbike' but found %v \n", motoBike.Structure)
    }
}

程序输出如下,


image.png

有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:FredricZhu

查看原文:Golang生成器模式

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1254 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传