天天看点

Go 语言 设计模式-装饰模式

装饰模式

概念示例

pizza.go: 零件接口

package main

type IPizza interface {
    getPrice() int
}      

veggieMania.go: 具体零件

package main

type VeggeMania struct {
}

func (p *VeggeMania) 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 := &VeggeMania{}

    //Add cheese topping
    pizzaWithCheese := &CheeseTopping{
        pizza: pizza,
    }

    //Add tomato topping
    pizzaWithCheeseAndTomato := &TomatoTopping{
        pizza: pizzaWithCheese,
    }

    fmt.Printf("Price of veggeMania with tomato and cheese topping is %d\n", pizzaWithCheeseAndTomato.getPrice())
}      

output.txt: 执行结果

Price of veggeMania with tomato and cheese topping is 32      

继续阅读