ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 要点 装饰器生成和组件相同的方法 ## 示例 ### demo ### 装饰模式(添加钩子) 格式: <details> <summary>main.go</summary> ``` package main import "fmt" //定义抽象的组件 type Component interface { Operate() } type Component1 struct { } func (c Component1) Operate() { fmt.Printf("%+v\n", "c1 operate") } // 定义一个抽象的装饰者 type Decorator interface { Component Do() //装饰行为,可以有多个 } //定义一个具体的装饰器 type Decorator1 struct { c Component } func (d Decorator1) Do() { fmt.Printf("%+v\n", "c1 发生了装饰行为") } // 重新实现component 的方法 func (d Decorator1) Operate() { d.Do() d.c.Operate() d.Do() } func main() { //无装饰模式 c1:=&Component1{} c1.Operate() //装饰模式 c2 :=&Decorator1{ c: c1, } c2.Operate() } ``` </details> <br /> ### 披萨价格 <details> <summary>main.go</summary> ``` package main import "fmt" // 零件接口 type pizza interface { getPrice() int } // 具体零件 type veggeMania struct { } func (p *veggeMania) getPrice() int { return 15 } // 具体装饰 type tomatoTopping struct { pizza pizza } func (c *tomatoTopping) getPrice() int { pizzaPrice := c.pizza.getPrice() return pizzaPrice + 7 } // 具体装饰 type cheeseTopping struct { pizza pizza } func (c *cheeseTopping) getPrice() int { pizzaPrice := c.pizza.getPrice() return pizzaPrice + 10 } // 客户端代码 func main() { pizza := &veggeMania{} pizzaWithCheese := &cheeseTopping{ pizza: pizza, } pizzaWithCheeseAndTomato := &tomatoTopping{ pizza: pizzaWithCheese, } fmt.Printf("披萨价格: %d\n", pizzaWithCheeseAndTomato.getPrice()) } ``` </details> <br /> 输出 ``` 披萨价格: 32 ```