模式定义
装饰模式(Decorator Pattern) :动态地给一个对象增加一些额外的职责(Responsibility),就增加对象功能来说,装饰模式比生成子类实现更为灵活。其别名也可以称为包装器(Wrapper),与适配器模式的别名相同,但它们适用于不同的场合。根据翻译的不同,装饰模式也有人称之为“油漆工模式”,它是一种对象结构型模式。
主要是给原始对象增强功能
模式结构
装饰模式包含如下角色:
Component: 抽象构件
ConcreteComponent: 具体构件
Decorator: 抽象装饰类
ConcreteDecorator: 具体装饰类
适用场景
在以下情况下可以使用装饰模式:
1.在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责。
2.需要动态地给一个对象增加功能,这些功能也可以动态地被撤销。
3.当不能采用继承的方式对系统进行扩充或者采用继承不利于系统扩展和维护时。不能采用继承的情况主要有两类:第一类是系统中存在大量独立的扩展,为支持每一种组合将产生大量的子类,使得子类数目呈爆炸性增长;第二类是因为类定义不能继承(如final类).
代码实现
package main
import (
"fmt"
)
// IDraw IDraw
type IDraw interface {
Draw() string
}
// Square 正方形
type Square struct{}
// Draw Draw
func (s Square) Draw() string {
return "this is a square"
}
// ColorSquare 有颜色的正方形
type ColorSquare struct {
square IDraw
color string
}
// NewColorSquare NewColorSquare
func NewColorSquare(square IDraw, color string) ColorSquare {
return ColorSquare{color: color, square: square}
}
// Draw Draw
func (c ColorSquare) Draw() string {
return c.square.Draw() + ", color is " + c.color
}
//主要是给原始对象增强功能
func main() {
result := NewColorSquare(new(Square), "red").Draw()
fmt.Println(result)
}
参考
https://design-patterns.readthedocs.io/zh_CN/latest/structural_patterns/decorator.html#id12