装饰器模式是一种结构型设计模式,该模式允许创建一系列装饰类来包装基础类的功能,以便在运行时动态地扩展该类的功能。
在 Go 中,我们可以使用函数作为装饰器。下面是一个示例:
type Component interface {
Operation() string
}
type ConcreteComponent struct{}
func (c *ConcreteComponent) Operation() string {
return "ConcreteComponent"
}
func Decorator(component Component) Component {
return &ConcreteDecorator{component}
}
type ConcreteDecorator struct {
component Component
}
func (d *ConcreteDecorator) Operation() string {
return "Decorated " + d.component.Operation()
}
在上面的示例中,我们定义了一个 Component
接口和一个基础类 ConcreteComponent
,它实现了 Operation()
方法。然后我们定义了一个 Decorator()
函数,它接收一个 Component
类型的参数,并返回一个新的装饰过的对象。
实现该函数的关键在于它返回的是一个新的装饰类,它包装了传递给它的 Component
对象。在此示例中,我们创建了一个 ConcreteDecorator
类,它实现了 Operation()
方法,并在基础类的实现中添加了一个字符串 "Decorated"。
下面是如何使用该装饰器模式来装饰类的示例:
func main() {
component := &ConcreteComponent{}
decorated := Decorator(component)
fmt.Println(decorated.Operation()) // Output: Decorated ConcreteComponent
}
在上面的示例中,我们首先创建了一个 ConcreteComponent
对象,并将其传递给 Decorator()
函数。该函数返回一个新的 ConcreteDecorator
对象,它包装了传递给它的 ConcreteComponent
对象。最终,我们调用 Operation()
方法以获得包装对象的输出。