实现装饰器模式示例,添加相关类和方法,增强代码可读性

This commit is contained in:
2026-01-01 00:41:28 +08:00
parent 29fd3f0557
commit 443e4f2352
3 changed files with 164 additions and 0 deletions
+66
View File
@@ -0,0 +1,66 @@
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("=========== 装饰器模式结束 ===========")
}