【寒江雪】Go实现Builder Pattern
2018-03-10 01:15
288 查看
Builder Pattern
生成器模式将复杂对象的构造与表示分开,以便相同的构建过程可以创建不同的表示形式。然而在Go语言中,如果向Builder传递一个结构,代码中就会充满检查代码,判断某个字段是否为空。为了避免这种现象,我们只需要在Builder中放置一个配置结构。
实现
我们来实现一个构造器构造一个灯的过程。// 先定义几个类型 type Color string type LampStatus bool type Brand string // 定义颜色常量 const ( BlueColor Color = "blue" GreenColor = "green" RedColor = "red" ) // 定义品牌常量 const ( OppleBulb Brand = "OPPLE" Osram = "OSRAM" ) // Lamp Builder define type Builder interface { Color(Color) LampBuilder Brand(Brand) LampBuilder Build() LampOperation } type LampBuilder struct { Lamp // 配置结构 } func (lb LampBuilder) Color(c Color) LampBuilder { lb.color=c return lb } func (lb LampBuilder) Brand(b Brand) LampBuilder { lb.brand=b return lb } func (lb LampBuilder) Build() LampOperation { // 新的产品产生过程 lamp := Lamp{color: lb.color, brand: lb.brand, status: false} return lamp } func NewBuilder() Builder { return LampBuilder{} } type LampOperation interface { Open() error Close() error Product 4000 ionIllustrative() } // 灯的定义 type Lamp struct { color Color brand Brand status LampStatus } func (l Lamp) Open() error { if l.status { return errors.New("Lamp is opened") } fmt.Println("Open lamp.") l.status = true return nil } func (l Lamp) Close() error { if !l.status { return errors.New("Lamp is closed") } fmt.Println("Close lamp.") l.status = true return nil; } func (l Lamp) ProductionIllustrative() { fmt.Println("I'm a lamp.") fmt.Println("Color:" + l.color) fmt.Println("Brand:" + l.brand) }
使用:
func main(){ b := builder.NewBuilder() lamp_1 := b.Color(builder.BlueColor).Brand(builder.Osram).Build() lamp_1.Open() lamp_1.ProductionIllustrative() lamp_2 := b.Color(builder.GreenColor).Brand(builder.OppleBulb).Build() lamp_2.ProductionIllustrative() }
Author:寒江雪
Date:2018 03 10
相关文章推荐
- 【寒江雪】Go实现单例模式
- 【寒江雪】Go实现观察者模式
- 【寒江雪】Go实现策略模式
- 【寒江雪】Go实现对象池模式
- 【寒江雪】Go实现装饰者模式
- 【寒江雪】Go实现迭代器模式
- 【寒江雪】Go实现桥接模式
- 【寒江雪】Go实现工厂模式
- 【寒江雪】Go实现命令模式
- 【寒江雪】Go实现备忘录
- 【寒江雪】Go实现组合模式
- 【寒江雪】Go实现外观模式
- 【寒江雪】Go实现责任链模式
- 【寒江雪】Go实现中介者模式
- 【寒江雪】Go实现状态模式
- 【寒江雪】Go实现模版方法模式
- 【寒江雪】Go实现代理模式
- GO语言JAVA语言实现的AES/CFB/256位的加密解密例子
- go语言实现通过FTP库自动上传web日志
- Go实战--golang实现生成缩略图服务器(disintegration/imaging、nfnt/resize)