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

相关推荐
二宝1522 小时前
黑马商城day4-微服务02
微服务·云原生·架构
小羊在睡觉2 小时前
golang定时器
开发语言·后端·golang
百锦再3 小时前
对前后端分离与前后端不分离(通常指服务端渲染)的架构进行全方位的对比分析
java·开发语言·python·架构·eclipse·php·maven
Mr_WangAndy4 小时前
C++设计模式_行为型模式_策略模式Strategy
c++·设计模式·策略模式·依赖倒置原则
不爱洗脚的小滕4 小时前
【Redis】三种缓存问题(穿透、击穿、双删)的 Golang 实践
redis·缓存·golang
LoveXming4 小时前
Chapter11—适配器模式
c++·设计模式·适配器模式·开闭原则
wuyunhang1234565 小时前
Docker----快速入门
docker·容器·架构
杯莫停丶5 小时前
设计模式之:单例模式
java·单例模式·设计模式
java_logo6 小时前
Docker 部署微服务项目保姆级教程
java·运维·docker·微服务·容器·eureka·架构
扁豆的主人6 小时前
架构设计过去十年与未来十年
架构