美文网首页
装饰模式

装饰模式

作者: 小幸运Q | 来源:发表于2021-02-26 10:02 被阅读0次

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

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()
}

相关文章

网友评论

      本文标题:装饰模式

      本文链接:https://www.haomeiwen.com/subject/npmsfltx.html