File tree Expand file tree Collapse file tree 2 files changed +55
-1
lines changed Expand file tree Collapse file tree 2 files changed +55
-1
lines changed Original file line number Diff line number Diff line change 41
41
5 . 将装饰基类扩展为具体装饰。具体装饰必须在调用父类方法(总是委派给被封装对象)之前或之后执行自身行为
42
42
6 . 客户端代码负责创建装饰并将其组合成客户端所需的形式
43
43
44
+
45
+ ### 装饰模式的优点和缺点
46
+
47
+ + 优点
48
+
49
+ + 你无需创建新子类即可扩展对象的行为
50
+ + 你可以在运行时添加或删除对象的功能
51
+ + 你可以用多个装饰封装对象来组合几种行为
52
+ + 单一职责原则。你可以将实现了许多不同行为的一个大类拆分成多个较小的类
53
+ + 缺点
54
+
55
+ + 在封装器栈中删除特定封装器比较困难
56
+ + 实现行为不受装饰栈顺序影响的装饰比较困难
57
+ + 各层的初始化配置代码看上去可能会很糟糕
58
+
Original file line number Diff line number Diff line change 1
1
package main
2
2
3
- func main () {
3
+ import (
4
+ "fmt"
5
+ )
4
6
7
+ // decorating moded 能够无限套娃,这个基类的成员变量的作用非常关键***
8
+ func main () {
9
+ pizza := & VeggieMania {}
10
+ pizzaWithCheese := & CheeseTopping {
11
+ pizza : pizza ,
12
+ }
13
+ pizzaWithCheeseAndTomato := & TomatoTopping {
14
+ pizza : pizzaWithCheese ,
15
+ }
16
+ fmt .Printf ("Price of veggeMania with tomato and cheese topping is %d\n " , pizzaWithCheeseAndTomato .getPrice ())
5
17
}
6
18
7
19
//零件接口
8
20
type IPizza interface {
9
21
getPrice () int
10
22
}
23
+
24
+ // 具体零件
25
+ type VeggieMania struct {
26
+ }
27
+
28
+ func (p * VeggieMania ) getPrice () int {
29
+ return 15
30
+ }
31
+
32
+ // 具体装饰
33
+ type TomatoTopping struct {
34
+ pizza IPizza
35
+ }
36
+
37
+ func (c * TomatoTopping ) getPrice () int {
38
+ pizzaPrice := c .pizza .getPrice ()
39
+ return pizzaPrice + 7
40
+ }
41
+
42
+ type CheeseTopping struct {
43
+ pizza IPizza
44
+ }
45
+
46
+ func (c * CheeseTopping ) getPrice () int {
47
+ pizzaPrice := c .pizza .getPrice ()
48
+ return pizzaPrice + 10
49
+ }
You can’t perform that action at this time.
0 commit comments