用于代替继承的技术,无需通过继承增加子类就能扩展对象的新功能。通过接口封装解决功能拓展的问题。
image.pngDecorator的Component{}指向不同的ConcreteComponent具体实现
ConcreteDecoratorA 继承 Decorator 负责实现具体的装饰器类(通过组合实现不同的Operation函数)。
image.pngpackage main
import "fmt"
type Component interface {
Operation()
}
type ConcreteComponent struct {
}
func (this *ConcreteComponent) Operation() {
fmt.Println("ConcreteComponent operation")
}
type Decorator struct {
C Component
}
func (this *Decorator) Operation() {
this.C.Operation()
}
type ConcreteDecoratorA struct {
Decorator
}
func (this *ConcreteDecoratorA) Operation() {
this.Decorator.C.Operation()
fmt.Println("---ConcreteDecorator---")
}
func main() {
D := Decorator{&ConcreteComponent{}}
c1 := &ConcreteDecoratorA{D}
c1.Operation()
}
网友评论