[设计模式 Go实现] 结构型~装饰模式

装饰模式使用对象组合的方式动态改变或增加对象行为。

Go语言借助于匿名组合和非入侵式接口可以很方便实现装饰模式。

使用匿名组合,在装饰器中不必显式定义转调原对象方法。

decorator.go
go 复制代码
package decorator

type Component interface {
    Calc() int
}

type ConcreteComponent struct{}

func (*ConcreteComponent) Calc() int {
    return 0
}

type MulDecorator struct {
    Component
    num int
}

func WarpMulDecorator(c Component, num int) Component {
    return &MulDecorator{
        Component: c,
        num:       num,
    }
}

func (d *MulDecorator) Calc() int {
    return d.Component.Calc() * d.num
}

type AddDecorator struct {
    Component
    num int
}

func WarpAddDecorator(c Component, num int) Component {
    return &AddDecorator{
        Component: c,
        num:       num,
    }
}

func (d *AddDecorator) Calc() int {
    return d.Component.Calc() + d.num
}
decorator_test.go
go 复制代码
package decorator

import "fmt"

func ExampleDecorator() {
    var c Component = &ConcreteComponent{}
    c = WarpAddDecorator(c, 10)
    c = WarpMulDecorator(c, 8)
    res := c.Calc()

    fmt.Printf("res %d\n", res)
    // Output:
    // res 80
}
相关推荐
Dxy12393102161 天前
Python 使用正则表达式将多个空格替换为一个空格
开发语言·python·正则表达式
故事和你911 天前
洛谷-数据结构1-1-线性表1
开发语言·数据结构·c++·算法·leetcode·动态规划·图论
sg_knight1 天前
设计模式实战:命令模式(Command)
python·设计模式·命令模式
techdashen1 天前
Rust项目公开征测:Cargo 构建目录新布局方案
开发语言·后端·rust
星空椰1 天前
JavaScript 进阶基础:函数、作用域与常用技巧总结
开发语言·前端·javascript
忒可君1 天前
C# winform 自制分页功能
android·开发语言·c#
Rust研习社1 天前
Rust 智能指针 Cell 与 RefCell 的内部可变性
开发语言·后端·rust
leaves falling1 天前
C++模板进阶
开发语言·c++
坐吃山猪1 天前
Python27_协程游戏理解
开发语言·python·游戏
gCode Teacher 格码致知1 天前
Javascript提高:小数精度和随机数-由Deepseek产生
开发语言·javascript·ecmascript