装饰模式

2021-02-26  本文已影响0人  小幸运Q

用于代替继承的技术,无需通过继承增加子类就能扩展对象的新功能。通过接口封装解决功能拓展的问题。

image.png

Decorator的Component{}指向不同的ConcreteComponent具体实现

ConcreteDecoratorA 继承 Decorator 负责实现具体的装饰器类(通过组合实现不同的Operation函数)。

image.png
package 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()
}
上一篇 下一篇

猜你喜欢

热点阅读