《golang设计模式》第二部分·结构型模式-04-装饰器模式(Decorator)

文章目录

1.概述

一个原有类需要扩展,写一个装饰器来实现对原始类的扩展。

1.1 说明

  • Component(抽象组件):定义了原始对象的接口,装饰器也会实现这个接口。
  • Concrete Component(具体组件):原始对象,以后装饰器会装饰它。
  • Decorator(抽象装饰器):关联/聚合了抽象组件,并实现了抽象组件接口。
  • Concrete Decorator(具体装饰器):继承或实现了抽象装饰器,负责向抽象组件添加新的功能。

1.2 类图

<<interface>> Component +Server() ConcreteComponent +Server() Decorator +Server() ConcreteDecoratorA +Server() ConcreteDecoratorB +Server()

2.代码示例

2.1代码

go 复制代码
package main

import "fmt"

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

// 定义一个具体组件
type ConcreteComponent struct {
	name string
}

// 具体组件有一个查看方法
func (c *ConcreteComponent) Get() {
	fmt.Printf("%+v\n", c)
}

// 定义一个装饰器,它实现了抽象组件,同时它也依赖了抽象组件
type Decorator struct {
	Component   Component
	DecorationA string
	DecorationB string
}

func (d *Decorator) Get() {
	d.Component.Get()
	fmt.Printf("实现装饰:%q,%q", d.DecorationA, d.DecorationB)
}

//创建一个具体装饰器A
type DecoratorA struct {
	Decorator *Decorator
}

//Set模式扩展功能
func (d *DecoratorA) Set(decoration string) {
	d.Decorator.DecorationA = decoration
}
//创建一个装饰器B
type DecoratorB struct {
	Decorator *Decorator
	//DecorationA string
}
//Set模式扩展功能
func (d DecoratorB) Set(decoration string) {
	d.Decorator.DecorationB = decoration
}

func main() {
	//已经有一个具体组件如下
	concreteComponent := &ConcreteComponent{
		name: "马户",
	}

	//下边用装饰器扩展一些功能
	//实例化一个装饰器
	decorator := &Decorator{
		Component: concreteComponent,
	}

	//实例化具体装饰器A
	decoratorA := DecoratorA{
		Decorator: decorator,
	}
	//用装饰器A装饰
	decoratorA.Set("两耳垂肩")

	//实例化一个装饰器B
	decoratorB := DecoratorB{
		Decorator: decorator,
	}
	//用装饰器B装饰
	decoratorB.Set("三孔鼻")

	//查看结果
	decorator.Get()
}
  • 输出
shell 复制代码
&{name:马户}
实现装饰:"两耳垂肩","三孔鼻"

2.2 示例的类图

设计中,我们并没有一个抽象的装饰器,而是每个实际的装饰器都继承了worker;
<<interface>> Component +Get() ConcreteComponent +Name:string +Get() Decorator +Component:Component +DecorationA:string +DecorationB:string +Get() DecoratorA +Decorator *Decorator +Set() DecoratorB +Decorator *Decorator +Set()

相关推荐
xcLeigh3 分钟前
Go入门:短变量声明的陷阱与最佳实践
java·redis·golang·教程·变量
JavaPub-rodert19 分钟前
我又把自己的 Go 后台管理系统升级了一遍:文件管理、2GB 上传、私有文件预览、Docker 镜像全安排上了
开发语言·docker·golang·shiyuadmin
cxr82832 分钟前
从“对象本体”到“关系本体”
人工智能·架构
名字还没想好☜1 小时前
Go 的 sync.Cond 实战:用条件变量做等待/通知,比忙轮询省 CPU
开发语言·数据库·后端·golang·go
FII工业富联科技服务1 小时前
制造业AI规模化落地架构:从Task Agent到Factory Agent Brain的三级智能体演进解析
大数据·人工智能·架构
敲代码的玉米C1 小时前
我修的那个 bug,制造了另一个 bug
前端·人工智能·架构
yurenpai(27届找实习中)2 小时前
从销售订单推送 MES 看懂微服务调用(二):DTO 转换与 OpenFeign 调用
java·微服务·架构·服务调用
AustinXu2 小时前
从 Claude Code 到 Claude Tag,Harness Engineering 走到了组织这一层
设计模式·团队管理
剧中有戏2 小时前
单例模式从入门到精通:一个数据库连接池的完整剖析
设计模式
SamDeepThinking2 小时前
第3篇:企业级CAS单点登录实战-技术架构设计方案
后端·程序员·架构