专业编程基础技术教程

网站首页 > 基础教程 正文

设计模式-装饰器

ccvgpt 2024-08-04 12:16:38 基础教程 11 ℃

装饰器模式

一种动态地往一个类中添加新的行为的设计模式

就功能而言,修饰模式相比生成子类更为灵活,这样可以给某个而不是整个类添加一些功能

设计模式-装饰器

它是对象结构型模式




定义一个抽象组件Component,具体组件Component1,抽象的装饰者Decorator,具体的装饰者Decorator1

package demo4_1

import "fmt"

// Component 定义一个抽象的组件
type Component interface {
  Operate()
}

//Component1  实现一个具体的组件
type Component1 struct {
  
}

func (c1 *Component1) Operate()  {
  fmt.Println("c1 operate")
}

//Decorator 定义个一个抽象的装饰者
type Decorator interface {
  Component
  Do() //这是额外的方法
}

//Decorator1 实现一个具体的装饰者
type Decorator1 struct {
  c Component
}

func (c1 *Decorator1)Do()  {
  fmt.Println("c1 发生了装饰行为")
}

func (c1 *Decorator1)Operate()  {
  c1.Do()
  c1.c.Operate()
}

测试

package demo4_1

import "testing"

func TestComponent1_Operate(t *testing.T) {
  c1 := &Component1{}
  c1.Operate()
}

func TestDecorator1_Operate(t *testing.T) {
  d1 := &Decorator1{}
  c1 := &Component1{}
  d1.c = c1
  d1.Operate()
}

运行结果

=== RUN   TestDecorator1_Operate
c1 发生了装饰行为
c1 operate
--- PASS: TestDecorator1_Operate (0.00s)
PASS

Process finished with the exit code 0

最近发表
标签列表