[设计模式 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
}
相关推荐
一晌小贪欢3 小时前
【Python数据分析】数据分析与可视化
开发语言·python·数据分析·数据可视化·数据清洗
草莓火锅5 小时前
用c++使输入的数字各个位上数字反转得到一个新数
开发语言·c++·算法
j_xxx404_5 小时前
C++ STL:阅读list源码|list类模拟|优化构造|优化const迭代器|优化迭代器模板|附源码
开发语言·c++
DreamNotOver5 小时前
批量转换论文正文引用为上标
开发语言·论文上标
散峰而望5 小时前
C/C++输入输出初级(一) (算法竞赛)
c语言·开发语言·c++·算法·github
fie88895 小时前
基于MATLAB的狼群算法实现
开发语言·算法·matlab
gihigo19986 小时前
MATLAB中生成混淆矩阵
开发语言·matlab·矩阵
曾几何时`6 小时前
C++——this指针
开发语言·c++
小冯的编程学习之路6 小时前
【C++】: C++基于微服务的即时通讯系统(1)
开发语言·c++·微服务
码上淘金7 小时前
在 YAML 中如何将 JSON 对象作为字符串整体赋值?——兼谈 Go Template 中的 fromJson 使用
java·golang·json