结构型 - 3. 装饰器模式

114 阅读1分钟

装饰器模式,亦称:装饰模式、装饰者模式、Wrapper、Decorator

1. 装饰器模式解决的问题

装饰器模式主要解决继承关系过于复杂的问题,通过组合来代替继承。相对于简单的组合关系,还有两个比较特殊的地方:

  • 装饰器类和原始类继承同样的父类

    可以对原始类“嵌套”多个装饰器类。为满足这个应用场景,在设计的时候,装饰器类需要跟原始类继承相同的抽象类或接口。

  • 装饰器类是对功能的增强

    装饰器类附加的是跟原始类相关的增强功能;代理模式附加的是跟原始类无关的功能。

2. 装饰器的代码实现


type pizza interface {
   getPrice() int
}

type peppyPaneer struct {
}

func (p *peppyPaneer) getPrice() int {
   return 20
}

type veggeMania struct {
}

func (p *veggeMania) getPrice() int {
   return 15
}

type cheeseTopping struct {
   pizza pizza
}

func (c *cheeseTopping) getPrice() int {
   pizzaPrice := c.pizza.getPrice()
   return pizzaPrice + 10
}

type tomatoTopping struct {
   pizza pizza
}

func (c *tomatoTopping) getPrice() int {
   pizzaPrice := c.pizza.getPrice()
   return pizzaPrice + 7
}

// 客户端使用
func TestPizza(t *testing.T) {

   veggiePizza := &veggeMania{}

   //Add cheese topping
   veggiePizzaWithCheese := &cheeseTopping{
      pizza: veggiePizza,
   }

   //Add tomato topping
   veggiePizzaWithCheeseAndTomato := &tomatoTopping{
      pizza: veggiePizzaWithCheese,
   }

   t.Logf("Price of veggieMania pizza with tomato and cheese topping is %d\n", veggiePizzaWithCheeseAndTomato.getPrice())

   peppyPaneerPizza := &peppyPaneer{}
   // Add tomato topping
   peppyPaneerPizzaWithTomato := &tomatoTopping{pizza: peppyPaneerPizza}

   //Add cheese topping
   peppyPaneerPizzaWithTomatoAndCheese := &cheeseTopping{
      pizza: peppyPaneerPizzaWithTomato,
   }

   t.Logf("Price of peppyPaneer with tomato and cheese topping is %d\n", peppyPaneerPizzaWithTomatoAndCheese.getPrice())

}