装饰器模式(Decorator Pattern)

244 阅读2分钟

1、定义

1.1 模式引入

什么是装饰器模式?在日常生活中我们买了毛坯房后,需要对房子在原有的基础上进行装修。这种就是装饰器的应用

1.2 模式定义

装饰器模式(Decorator Pattern)是一种在不修改结构的基础上面,对对象添加新功能。这种设计模式属于结构型模式

2、组成角色

  • 抽象构件(Component):是原始的对象,用于定义抽象的接口或功能
  • 具体构件(ConcreteComponent):是实现抽象构建的接口方法,在装饰器模式中是被修饰的对象
  • 抽象装饰角色(Decorator):是定义修饰器的角色,用于定义修饰器的接口或功能
  • 具体修饰角色(ConcreteDecorator):是实现抽象装饰器的接口方法

image.png

3、应用场景

  • 在扩展某个对象的功能的时候,避免使用集成或组合的形式使得越来越臃肿,则可以使用装饰器模式进行实现

4、设计要点

  • 装饰器和被修饰类可以独立发展,不相互耦合
  • 避免使用多层修饰器嵌套,会使程序变更复杂

5、实现模板

  • 定义被修饰组件抽象interface
  • 定义被修饰组件struct,并实现被修饰组件抽象interface方法
  • 定义修饰器的抽象interface
  • 定义修饰器的struct,实现【被修饰组件抽象interface】的方法和【修饰器的抽象interface】的接口

6、实现示例

定义修饰器模式:

package decorator

import "fmt"

// 测试组件接口
type TestRunnerComponent interface {
   Run() error
}

// 定义GO语言测试组件,被修饰对象
type GoTestRunnerComponent struct {
   TestCase []string
}

// 实现测试组件(TestRunnerComponent)接口Run方法
func (c *GoTestRunnerComponent) Run() error {
   fmt.Println("修饰器模式!!!")
   return nil
}

// 定义测试报告修饰器接口
type TestReportDecorator interface {
   create() error
   save() error
}

// 定义GO测试组件具体修饰器
type GoTestComponentWithReport struct {
   TestRunner TestRunnerComponent
}

// 实现测试组件(TestRunnerComponent)接口run方法
func (c *GoTestComponentWithReport) Run() error {
   c.create()
   c.TestRunner.Run()
   c.save()

   return nil
}

// 实现测试修饰器(TestReportDecorator)接口create方法
func (c *GoTestComponentWithReport) create() error {
   return nil
}

// 实现测试修饰器(TestReportDecorator)接口save方法
func (c *GoTestComponentWithReport) save() error {
   return nil
}

调用修饰器模式:

package main

import "github.com/design/pattern/decorator"

func main() {
   // 过滤器模式
   testComponent := decorator.GoTestComponentWithReport{
      TestRunner: &decorator.GoTestRunnerComponent{
         TestCase: []string{
            "测试用例1",
            "测试用例2",
         },
      },
   }
   // 运行测试
   testComponent.Run()
}