File tree 3 files changed +64
-0
lines changed
3 files changed +64
-0
lines changed Original file line number Diff line number Diff line change
1
+ # 装饰模式
2
+
3
+ 装饰模式使用对象组合的方式动态改变或增加对象行为。
4
+
5
+ Go语言借助于匿名组合和非入侵式接口可以很方便实现装饰模式。
6
+
7
+ 使用匿名组合,在装饰器中不必显式定义转调原对象方法。
Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments