装饰器模式(Decorator Pattern)是一种结构型设计模式,允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有类的一个包装。
装饰器模式通常包含以下几个要素:
以下是使用Go语言实现装饰器模式的示例:
package main
import "fmt"
// 组件接口
type Component interface {
Operation() string
}
// 具体组件
type ConcreteComponent struct{}
func (c *ConcreteComponent) Operation() string {
return "ConcreteComponent"
}
// 装饰器
type Decorator struct {
component Component
}
func NewDecorator(component Component) *Decorator {
return &Decorator{component: component}
}
func (d *Decorator) Operation() string {
return d.component.Operation()
}
// 具体装饰器
type ConcreteDecoratorA struct {
*Decorator
}
func NewConcreteDecoratorA(component Component) *ConcreteDecoratorA {
return &ConcreteDecoratorA{NewDecorator(component)}
}
func (d *ConcreteDecoratorA) Operation() string {
return "ConcreteDecoratorA: " + d.Decorator.Operation()
}
type ConcreteDecoratorB struct {
*Decorator
}
func NewConcreteDecoratorB(component Component) *ConcreteDecoratorB {
return &ConcreteDecoratorB{NewDecorator(component)}
}
func (d *ConcreteDecoratorB) Operation() string {
return "ConcreteDecoratorB: " + d.Decorator.Operation()
}
func main() {
component := &ConcreteComponent{}
decoratorA := NewConcreteDecoratorA(component)
decoratorB := NewConcreteDecoratorB(decoratorA)
fmt.Println(decoratorB.Operation())
}
装饰器模式适用于以下场景:
优点:
缺点:
装饰器模式提供了一种灵活的替代扩展功能的方式,比继承更加灵活。它通过创建一系列装饰器来扩展功能,避免了使用继承造成的静态功能增加。