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

相关推荐
艾伦~耶格尔9 小时前
Spring Boot 三层架构开发模式入门
java·spring boot·后端·架构·三层架构
__AtYou__9 小时前
Golang | Leetcode Golang题解之第448题找到所有数组中消失的数字
leetcode·golang·题解
千年死缓11 小时前
go+redis基于tcp实现聊天室
redis·tcp/ip·golang
_.Switch13 小时前
Python机器学习框架介绍和入门案例:Scikit-learn、TensorFlow与Keras、PyTorch
python·机器学习·架构·tensorflow·keras·scikit-learn
吃着火锅x唱着歌15 小时前
Redis设计与实现 学习笔记 第五章 跳跃表
golang
技术卷18 小时前
Redis数据库与GO完结篇:redis操作总结与GO使用redis
数据库·redis·golang
神一样的老师19 小时前
构建5G-TSN测试平台:架构与挑战
5g·架构
huaqianzkh19 小时前
付费计量系统通用功能(13)
网络·安全·架构
2402_8575834920 小时前
新闻推荐系统:Spring Boot的架构优势
数据库·spring boot·架构
white.tie20 小时前
vscode配置golang
ide·vscode·golang