[设计模式 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
}
相关推荐
千千寰宇15 小时前
[设计模式/Java/多线程] 设计模式之单例模式【9】
设计模式·操作系统-进程/线程/并发
我不会编程55521 小时前
Python Cookbook-5.1 对字典排序
开发语言·数据结构·python
李少兄21 小时前
Unirest:优雅的Java HTTP客户端库
java·开发语言·http
此木|西贝21 小时前
【设计模式】原型模式
java·设计模式·原型模式
无名之逆21 小时前
Rust 开发提效神器:lombok-macros 宏库
服务器·开发语言·前端·数据库·后端·python·rust
似水এ᭄往昔1 天前
【C语言】文件操作
c语言·开发语言
啊喜拔牙1 天前
1. hadoop 集群的常用命令
java·大数据·开发语言·python·scala
xixixin_1 天前
为什么 js 对象中引用本地图片需要写 require 或 import
开发语言·前端·javascript
W_chuanqi1 天前
安装 Microsoft Visual C++ Build Tools
开发语言·c++·microsoft
anlogic1 天前
Java基础 4.3
java·开发语言