[设计模式 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
}
相关推荐
IT=>小脑虎13 小时前
C++零基础衔接进阶知识点【详解版】
开发语言·c++·学习
nbsaas-boot13 小时前
Go vs Java 的三阶段切换路线图
java·开发语言·golang
码农小韩13 小时前
基于Linux的C++学习——指针
linux·开发语言·c++·学习·算法
微露清风13 小时前
系统性学习C++-第十九讲-unordered_map 和 unordered_set 的使用
开发语言·c++·学习
BBBBBAAAAAi13 小时前
Claude Code安装记录
开发语言·前端·javascript
毕设源码-钟学长13 小时前
【开题答辩全过程】以 基于Java的慕课点评网站为例,包含答辩的问题和答案
java·开发语言
maozexijr13 小时前
Rabbit MQ中@Exchange(durable = “true“) 和 @Queue(durable = “true“) 有什么区别
开发语言·后端·ruby
深圳佛手13 小时前
使用java,怎么样高效地读取一个大文件(10g以上)?
java·开发语言
xiaolyuh12313 小时前
【XXL-JOB】 GLUE模式 底层实现原理
java·开发语言·前端·python·xxl-job
源码获取_wx:Fegn089513 小时前
基于 vue智慧养老院系统
开发语言·前端·javascript·vue.js·spring boot·后端·课程设计