[设计模式 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
}
相关推荐
鱼鱼说测试29 分钟前
postman接口自动化测试
开发语言·lua
從南走到北35 分钟前
JAVA国际版东郊到家同城按摩服务美容美发私教到店服务系统源码支持Android+IOS+H5
android·java·开发语言·ios·微信·微信小程序·小程序
_不会dp不改名_1 小时前
C++ 20: Concepts 与Requires
开发语言·c++20
韭菜钟1 小时前
Qt从qmake迁移到cmake的记录
开发语言·qt
少陵野小Tommy2 小时前
Python能用古诗词数据库做什么7:根据标题、诗句查找诗歌
开发语言·数据库·python
长城20242 小时前
PHP如何使用JpGraph生成3D饼形图?
开发语言·php·jpgraph·3d饼形图
AlenLi3 小时前
JavaScript - 观察者模式的实现与应用场景
前端·设计模式
우리帅杰4 小时前
【golang】ORM框架操作数据库
golang
秦禹辰4 小时前
本地Docker部署开源Web相册图库Piwigo与在线远程访问实战方案
开发语言·后端·golang
the beard4 小时前
深入理解Java多线程:状态、安全、同步与通信
java·开发语言