动态地将责任附加到对象上。提供有别于继承的另一种扩展功能的选择。
package main
import "fmt"
//抽象组件
type AbstractBeverage interface{
getDescription() string
cost()float64
}
type Beverage struct{
description string
}
func (b Beverage) getDescription() string{
return b.description
}
//具体组件
type BlackCoffe struct{
Beverage
}
func NewBlackCoffe() BlackCoffe{
res := BlackCoffe{}
res.description = "BlackCoffe"
return res
}
func (c BlackCoffe) cost() float64{
return 12
}
type WhiteCoffe struct{
Beverage
}
func NewWhiteCoffe() WhiteCoffe{
res := WhiteCoffe{}
res.description = "WhiteCoffe"
return res
}
func (w WhiteCoffe) cost() float64{
return 18
}
//具体装饰者
type Sugar struct{
beverage AbstractBeverage
}
func NewSugar(b AbstractBeverage) Sugar{
res:= Sugar{}
res.beverage = b
return res
}
func (s Sugar) getDescription() string{
return s.beverage.getDescription() + "-" +"Sugar"
}
func (s Sugar) cost() float64{
return 0.2 + s.beverage.cost()
}
func main () {
var coffe AbstractBeverage
coffe = NewWhiteCoffe()
coffe = NewSugar(coffe)
coffe = NewSugar(coffe)
fmt.Println("name:",coffe.getDescription(),"cost:",coffe.cost())
}