代码实现

下面是一个简单的画画的例子,默认的 Line  只有基础的画画功能, ColorLine  为他加上了颜色,本质上是对现有功能类进行包装,增加新功能点

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package decorator  

// IDraw IDraw
type IDraw interface {
Draw() string
}

// Line 划线
type Line struct{}

// Draw Draw
func (l Line) Draw() string {
return "Drawing a line here"
}

// ColorLine 有颜色的线
type ColorLine struct {
line IDraw
color string
}

// NewColorLine NewColorLine
func NewColorLine(line IDraw, color string) ColorLine {
return ColorLine{color: color, line: line}
}

// Draw Draw
func (c ColorLine) Draw() string {
return c.line.Draw() + ", color is " + c.color
}

单元测试

1
2
3
4
5
6
func TestColorLine_Draw(t *testing.T) {  
l := Line{}
ncl := NewColorLine(sq, "red")
got := ncl.Draw()
assert.Equal(t, "Drawing a line here, color is red", got)
}