装饰者模式
装饰者模式
统一接口
package decorator
type decorator interface {
getPrice() uint8
getDesc() string
}
炒饭(被装饰者)
package decorator
type rice struct {
price uint8
}
func NewRice(price uint8) *rice {
return &rice{price: price}
}
func (r *rice) getPrice() uint8 {
return r.price
}
func (r *rice) getDesc() string {
return "白炒饭"
}
炒面(被装饰者)
package decorator
type noodles struct {
price uint8
}
func NewNoodles(price uint8) *noodles {
return &noodles{price: price}
}
func (n *noodles) getPrice() uint8 {
return n.price
}
func (n *noodles) getDesc() string {
return "素炒面"
}
鸡蛋(装饰者)
package decorator
type egg struct {
decorator
price uint8
}
func NewEgg(d decorator, price uint8) decorator {
return &egg{
decorator: d,
price: price,
}
}
func (e *egg) getPrice() uint8 {
return e.price + e.decorator.getPrice()
}
func (e *egg) getDesc() string {
return e.decorator.getDesc() + "加蛋"
}
火腿肠
package decorator
type ham struct {
decorator
price uint8
}
func NewHam(d decorator, price uint8) decorator {
return &ham{
decorator: d,
price: price,
}
}
func (h *ham) getPrice() uint8 {
return h.price + h.decorator.getPrice()
}
func (h *ham) getDesc() string {
return h.decorator.getDesc() + "加火腿肠"
}
测试文件
package decorator
func TestDecorator(t *testing.T) {
r := NewRice(10)
re := NewEgg(r, 2)
reh := NewHam(re, 3)
fmt.Println(reh.getPrice(), reh.getDesc())
n := NewNoodles(8)
ne := NewEgg(n, 2)
nee := NewEgg(ne, 3)
fmt.Println(nee.getPrice(), nee.getDesc())
}

浙公网安备 33010602011771号