【Go-设计模式】装饰器模式 详解

概念:
动态地将 新功能 附加到对象上
在 对象功能扩展 方面,它比 继承 更有弹性,装饰者模式也体现了 开闭原则(ocp)
装饰器模式 就像 打包一个快递
主体(被装饰者):比如:陶瓷、衣服 (Component)
包装(装饰器):比如:报纸填充、塑料泡沫、纸板、木板(Decorator)

UML:

- Component:
主体功能接口,定义主体类的主要功能 - ConcreteComponent:
具体的主体类,主体功能的具体实现 - Decorator:
装饰器功能接口,定义装饰器的功能 - ConcreteDecorator:
具体的装饰器,装饰器逻辑的具体实现
示例
主体:
type Component interface {
Desc() string
}
具体的主体:
type ConcreteComponent struct {
Description string
}
func (this ConcreteComponent) Desc() string {
return this.Description
}
装饰器:
type Decorator struct {
Component
additionalDesc string
}
func WrapComponent(component Component, desc string) Component {
return Decorator{
Component: component,
additionalDesc: desc,
}
}
func (this Decorator) Desc() string {
return this.Component.Desc() + ":" + this.additionalDesc
}
测试:
package main
import (
"DemoProject/design/base23/decorator" // 根据自己的项目路径定制
"fmt"
)
func main() {
// decorator
var component decorator.Component = &decorator.ConcreteComponent{
Description: "Golang",
}
component = decorator.WrapComponent(component, "天然支持高并发")
res := component.Desc()
fmt.Printf(res)
}

浙公网安备 33010602011771号