Go 装饰模式

155 阅读2分钟

装饰模式是一种结构型的设计模式,它允许你动态地将行为添加到对象中,在不必改变其原有类结构的前提下进行拓展。在这种模式中,装饰器类负责包装原有类,并提供额外的功能,而原有类则可以保持不变。

Golang 作为一种开源的编程语言,也支持装饰模式的实现。下面我们将演示一下如何使用装饰模式为一个基础的文本组件添加一些额外的功能。

类定义

我们首先定义一个文本组件的接口,它有一个 render() 方法,用于展示组件的内容。

type TextComponent interface {
    render() string
}

接下来,我们定义一个基础的文本组件,它实现了 TextComponent 接口,并在 render() 方法中展示了组件的内容。

type BaseTextComponent struct {
    content string
}

func (btc BaseTextComponent) render() string {
    return btc.content
}

装饰器实现

现在,我们将创建一些装饰器来拓展这个基础文本组件的功能。首先,我们创建一个大写字母装饰器,它将文本组件中的所有字母转换成大写字母。

type UppercaseDecorator struct {
    textComponent TextComponent
}

func (ud UppercaseDecorator) render() string {
    return strings.ToUpper(ud.textComponent.render())
}

接下来,我们创建一个颜色装饰器,它为文本组件添加一些颜色。

type ColorDecorator struct {
    textComponent TextComponent
    color         string
}

func (cd ColorDecorator) render() string {
    return fmt.Sprintf("\033[%sm%s\033[0m", cd.color, cd.textComponent.render())
}

使用

现在,我们可以创建一个基础的文本组件,并使用装饰器为它添加样式。

func main() {
    baseComponent := BaseTextComponent{content: "hello world"}

    uppercaseComponent := UppercaseDecorator{textComponent: baseComponent}
    colorComponent := ColorDecorator{textComponent: uppercaseComponent, color: "31"}

    fmt.Println(colorComponent.render())
}

通过运行上面的代码,我们可以在终端上看到“HELLO WORLD”字样,并加上了红色。这就是装饰器模式的效果。通过不断地叠加装饰器,我们可以为一个基础组件添加无数种组合样式。