设计模式不分语言,是一种思维层面的体现,但是不能在不同语言中使用同一套实现(每种语言有不同的特性),比如go,本身是没有继承一说,但是通过结构体的组合来实现语义上的继承。而多态也是通过接口的方式来实现的。

下方的图来自于大佬博客,贴在这里方便查看!!!

设计原则

在这里插入图片描述

设计模式

在这里插入图片描述

结构型模式

装饰器模式

主要解决继承关系过于复杂的问题,通过组合来代替继承,给目标类添加增强功能,作为包装。

type IDraw interface {
	Draw() string
}

type Square struct {
}

func (s *Square) Draw() string {
	return "我画了一个正方形"
}

type ColorSquare struct {
	square Square
	color  string
}

func NewColorSquare(square IDraw, color string) *ColorSquare {
	return &ColorSquare{square: Square{}, color: color}
}

func (c *ColorSquare) Draw() string {
	return c.square.Draw() + "颜色是 " + c.color
}

可能看起来这个和代理模式很像。
但是代理模式是用来抽出做通用模块的,一般适合业务本身无关的逻辑。而装饰者模式是和功能有增强关系的。