《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()

相关推荐
Web3&Basketball10 小时前
CRM Agent 后训练实战:3 倍更少错误
python·架构·大模型·agent·推理
ting945200014 小时前
深度拆解Enter Pro AI原生开发平台:从底层架构到企业级落地技术实践
人工智能·架构·ai-native
这个DBA有点耶15 小时前
数据库集群与分布式架构:三条技术路线对比、金仓KES RAC实测数据与决策框架
数据库·程序员·架构
这个DBA有点耶17 小时前
InnoDB页结构深入:页分裂、页合并、填充因子——B+树底层机制全解析
数据库·mysql·架构
Dawson Zhu17 小时前
大模型记忆系统设计:分层架构与关键技术解析
人工智能·语言模型·架构·aigc·agi
Dawson Zhu18 小时前
大模型预训练为何普遍单轮遍历?——从 Scaling Laws、数据重复到灾难性遗忘的技术解析
人工智能·语言模型·架构·aigc·agi
烈风逍遥19 小时前
第五篇:通用 LLM 流式对话:前后端联接的完整实现
前端·后端·架构
骑着蜗牛撵大象32719 小时前
告别内存泄漏:LLMManager架构设计与智能指针在AI SDK中的智慧选型
c++·ai·架构
怕浪猫20 小时前
一行命令复刻爆款视频,我把 Hypit 从安装跑到了出片
人工智能·设计模式·程序员
万联WANFLOW20 小时前
网络排障:如何从延迟、丢包、带宽定位海外访问异常
网络·架构·业界资讯