【设计模式】 装饰模式
装饰模式(Decorator Pattern)是一种结构型设计模式,它允许动态地给一个对象添加新的功能,而无需修改其源代码。在 Golang 中实现装饰模式可以使用接口和组合来实现。
下面是一个使用 Golang 实现装饰模式的示例代码:
package main
import "fmt"
type Component interface {
Operation()
}
type ConcreteComponent struct{}
func (c *ConcreteComponent) Operation() {
fmt.Println("ConcreteComponent.Operation()")
}
type Decorator interface {
Component
}
type ConcreteDecoratorA struct {
component Component
}
func (d *ConcreteDecoratorA) Operation() {
d.component.Operation()
fmt.Println("ConcreteDecoratorA.Operation()")
}
type ConcreteDecoratorB struct {
component Component
}
func (d *ConcreteDecoratorB) Operation() {
d.component.Operation()
fmt.Println("ConcreteDecoratorB.Operation()")
}
func main() {
component := &ConcreteComponent{}
decoratorA := &ConcreteDecoratorA{component}
decoratorB := &ConcreteDecoratorB{decoratorA}
decoratorB.Operation()
}
在上面的代码中,我们定义了一个 Component 接口,它包含一个 Operation 方法,用于执行操作。我们还定义了一个 ConcreteComponent 结构体,它实现了 Component 接口的 Operation 方法。
接着,我们定义了一个 Decorator 接口,它继承了 Component 接口,并定义了两个具体的装饰器类:ConcreteDecoratorA 和 ConcreteDecoratorB。这两个装饰器类都包含一个 component 成员变量,用于存储被装饰的组件对象。它们也都实现了 Operation 方法,该方法会先调用被装饰的组件对象的 Operation 方法,然后再执行自己的操作。
最后,在 main 函数中,我们创建了一个 ConcreteComponent 实例,并分别用 ConcreteDecoratorA 和 ConcreteDecoratorB 对其进行装饰。由于 ConcreteDecoratorA 和 ConcreteDecoratorB 都实现了 Component 接口,因此它们可以像 ConcreteComponent 一样被传递和使用。最终,我们调用 decoratorB.Operation() 方法,会先调用 ConcreteComponent.Operation() 方法,然后依次执行 ConcreteDecoratorA.Operation() 和 ConcreteDecoratorB.Operation() 方法。通过这种方式,我们可以动态地给一个对象添加新的功能,而无需修改其源代码。