设计模式——装饰者模式

动态地将责任附加到对象上。提供有别于继承的另一种扩展功能的选择。

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())
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值