1
0
Fork 0
design-patterns/go/decorator/main.go

67 lines
1.1 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import "fmt"
/*
实例
汤宝宝家有一台咖啡机,他会自动给美式咖啡加奶和糖...
*/
type Drink interface {
GetPrice() float64
cost()
}
type Coffee struct {
name string
Price float64
}
func (c *Coffee) GetPrice() float64 {
return c.Price
}
func (c *Coffee) cost() {
fmt.Printf("一杯%s咖啡价格%.2f元。\n", c.name, c.Price)
}
type Maker struct {
wrappedDrink Drink
milkPrice float64
sugarPrice float64
}
func (m *Maker) GetPrice() float64 {
return m.wrappedDrink.GetPrice()
}
func (m *Maker) cost() {
m.wrappedDrink.cost()
fmt.Printf("加了奶和糖,总价%.2f元。\n",
m.wrappedDrink.GetPrice()+m.milkPrice+m.sugarPrice)
}
func main() {
fmt.Println("============= 装饰器模式 =============")
var coffee, newCoffee Drink
fmt.Println("自己泡杯咖啡")
coffee = &Coffee{
name: "美式",
Price: 10.0,
}
coffee.cost()
fmt.Println("\n用咖啡机泡杯咖啡")
newCoffee = &Maker{
wrappedDrink: coffee,
milkPrice: 1.0,
sugarPrice: 1.0,
}
newCoffee.cost()
fmt.Println()
fmt.Println("=========== 装饰器模式结束 ===========")
}