Go 装饰模式讲解和代码示例

装饰是一种结构设计模式, 允许你通过将对象放入特殊封装对象中来为原对象增加新的行为。

由于目标对象和装饰器遵循同一接口, 因此你可用装饰来对对象进行无限次的封装。 结果对象将获得所有封装器叠加而来的行为。

概念示例

pizza.go: 零件接口

package main
type IPizza interface {
	getPrice() int
}

veggieMania.go: 具体零件

package main
type VeggieMania struct{}
func (p *VeggieMania) getPrice() int {
	return 15
}

tomatoTopping.go: 具体装饰

package main
type TomatoTopping struct {
	pizza IPizza
}
func (c *TomatoTopping) getPrice() int {
	pizzaPrice := c.pizza.getPrice()
	return pizzaPrice + 7
}

cheeseTopping.go: 具体装饰

package main
type CheeseTopping struct {
	pizza IPizza
}
func (c *CheeseTopping) getPrice() int {
	pizzaPrice := c.pizza.getPrice()
	return pizzaPrice + 10
}

main.go: 客户端代码

package main
import "fmt"
func main() {
	pizza := &VeggieMania{}
	pizzaWithCheese := &CheeseTopping{pizza: pizza}
	pizzaWithCheeseAndTomato := &TomatoTopping{
		pizza: pizzaWithCheese,
	}
	fmt.Printf("Price of veggeMania with tomato and cheese topping is %d\n", pizzaWithCheeseAndTomato.getPrice())
}

output.txt: 执行结果

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。