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

相关推荐
敲代码的 蜡笔小新2 分钟前
【行为型之迭代器模式】游戏开发实战——Unity高效集合遍历与场景管理的架构精髓
unity·设计模式·c#·迭代器模式
Kookoos1 小时前
Redis + ABP vNext 构建分布式高可用缓存架构
redis·分布式·缓存·架构·c#·.net
GISer_Jing2 小时前
React底层架构深度解析:从虚拟DOM到Fiber的演进之路
前端·react.js·架构
欧先生^_^7 小时前
rust语言,与c,go语言一样也是编译成二进制文件吗?
c语言·golang·rust
背帆18 小时前
go的interface接口底层实现
开发语言·后端·golang
MZWeiei19 小时前
Spark SQL 运行架构详解(专业解释+番茄炒蛋例子解读)
大数据·分布式·sql·架构·spark
#金毛19 小时前
一、HAL库的设计理念详解:从架构到实践
stm32·嵌入式硬件·架构
是麟渊19 小时前
【大模型面试每日一题】Day 17:解释MoE(Mixture of Experts)架构如何实现模型稀疏性,并分析其训练难点
人工智能·自然语言处理·面试·职场和发展·架构
好吃的肘子19 小时前
MongoDB 高可用复制集架构
数据库·mongodb·架构
TsingtaoAI19 小时前
医疗系统开发架构和技术路线建议-湖南某三甲医院
架构·医疗ai系统·医疗信息化·医疗系统架构·医疗ai机构