Skip to content

Commit 1bf2afb

Browse files
committed
add decorator
1 parent ad60e3c commit 1bf2afb

File tree

3 files changed

+64
-0
lines changed

3 files changed

+64
-0
lines changed

20_decorator/README.md

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# 装饰模式
2+
3+
装饰模式使用对象组合的方式动态改变或增加对象行为。
4+
5+
Go语言借助于匿名组合和非入侵式接口可以很方便实现装饰模式。
6+
7+
使用匿名组合,在装饰器中不必显式定义转调原对象方法。

20_decorator/decorator.go

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package decorator
2+
3+
type Component interface {
4+
Calc() int
5+
}
6+
7+
type ConcreteComponent struct{}
8+
9+
func (*ConcreteComponent) Calc() int {
10+
return 0
11+
}
12+
13+
type MulDecorator struct {
14+
Component
15+
num int
16+
}
17+
18+
func WarpMulDecorator(c Component, num int) Component {
19+
return &MulDecorator{
20+
Component: c,
21+
num: num,
22+
}
23+
}
24+
25+
func (d *MulDecorator) Calc() int {
26+
return d.Component.Calc() * d.num
27+
}
28+
29+
type AddDecorator struct {
30+
Component
31+
num int
32+
}
33+
34+
func WarpAddDecorator(c Component, num int) Component {
35+
return &AddDecorator{
36+
Component: c,
37+
num: num,
38+
}
39+
}
40+
41+
func (d *AddDecorator) Calc() int {
42+
return d.Component.Calc() + d.num
43+
}

20_decorator/decorator_test.go

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package decorator
2+
3+
import "fmt"
4+
5+
func ExampleDecorator() {
6+
var c Component = &ConcreteComponent{}
7+
c = WarpAddDecorator(c, 10)
8+
c = WarpMulDecorator(c, 8)
9+
res := c.Calc()
10+
11+
fmt.Printf("res %d\n", res)
12+
// Output:
13+
// res 80
14+
}

0 commit comments

Comments
 (0)