Go设计模式08-装饰器模式
序
- Go 设计模式实现,包含常见的设计模式实现,同时这也是 极客时间-设计模式之美 的笔记,源课程采用 Java 实现,本系列会采用 Go 实现
- 课程: 50 | 装饰器模式:通过剖析 Java IO 类库源码学习装饰器模式
- 本文代码仓库: https://github.com/mohuishou/go-design-pattern 🌟🌟🌟🌟🌟
- RoadMap: 08/22 持续更新中,预计一周更新 2 ~ 3 种设计模式,预计到 202010 月底前更新完成
- 获取更新: Github、知乎、RSS、开发者头条**
笔记
代码实现
下面是一个简单的画画的例子,默认的 Square
只有基础的画画功能, ColorSquare
为他加上了颜色
Code
package decorator
// IDraw IDraw
type IDraw interface {
Draw() string
}
// Square 正方形
type Square struct{}
// Draw Draw
func (s Square) Draw() string {
return "this is a square"
}
// ColorSquare 有颜色的正方形
type ColorSquare struct {
square IDraw
color string
}
// NewColorSquare NewColorSquare
func NewColorSquare(square IDraw, color string) ColorSquare {
return ColorSquare{color: color, square: square}
}
// Draw Draw
func (c ColorSquare) Draw() string {
return c.square.Draw() + ", color is " + c.color
}
单元测试
func TestColorSquare_Draw(t *testing.T) {
sq := Square{}
csq := NewColorSquare(sq, "red")
got := csq.Draw()
assert.Equal(t, "this is a square, color is red", got)
}
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!