Go 设计模式之装饰器模式
装饰者模式
动态地将责任附加到对象上。想要扩展功能,装饰者提供有别于继承的另一种选择。
装饰者模式 符合开放-关闭原则。继承 虽然属于扩展的形式之一,但是在设计中,推崇多用组合少用继承的说法。但是好像 GO 里面没有继承的说法,只有组合。所以用 GO 实现装饰者模式还是很方便的。装饰者的主要目的就是对基础对象不断的扩展功能,虽然在一定程度上保持了扩展性,但是如果过度使用会出现众多小对象,会使程序变得很复杂。
// 饮料接口
type Beverage interface {
getDescription() string
cost() int
}
// 实现咖啡的过程
type Coffee struct {
description string
}
func(this Coffee) getDescription() string {
return this.description
}
func(this Coffee) cost() int {
return 1
}
// Mocha 实现
type Mocha struct {
beverage Beverage
description string
}
func(this Mocha) getDescription() string {
return fmt.Sprintf("%s, %s", this.beverage.getDescription(), this.description)
}
func(this Mocha) cost() int {
return this.beverage.cost() + 1
}
// Whip 实现
type Whip struct {
beverage Beverage
description string
}
func(this Whip) getDescription() string {
return fmt.Sprintf("%s, %s", this.beverage.getDescription(), this.description)
}
func(this Whip) cost() int {
return this.beverage.cost() + 1
}
func main() {
var beverage Beverage
// 买了一杯咖啡
beverage = Coffee{description:"houseBlend"}
// 给咖啡加上 Mocha
beverage = Mocha{beverage:beverage, description:"Mocha"}
// 给咖啡加上 Whip
beverage = Whip{beverage:beverage, description:"whip"}
// 最后计算 Coffee 的价格
fmt.Println(beverage.getDescription(), ", cost is ", beverage.cost())
}
装饰模式是原始对象的扩展,不断的增加功能。
本作品采用《CC 协议》,转载必须注明作者和本文链接