Skip to content

Commit f15a2fa

Browse files
committed
additional decorating mode
1 parent 8666d81 commit f15a2fa

File tree

2 files changed

+55
-1
lines changed

2 files changed

+55
-1
lines changed

Design Mode/Decorating Mode.markdown

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,18 @@
4141
5. 将装饰基类扩展为具体装饰。具体装饰必须在调用父类方法(总是委派给被封装对象)之前或之后执行自身行为
4242
6. 客户端代码负责创建装饰并将其组合成客户端所需的形式
4343

44+
45+
### 装饰模式的优点和缺点
46+
47+
+ 优点
48+
49+
+ 你无需创建新子类即可扩展对象的行为
50+
+ 你可以在运行时添加或删除对象的功能
51+
+ 你可以用多个装饰封装对象来组合几种行为
52+
+ 单一职责原则。你可以将实现了许多不同行为的一个大类拆分成多个较小的类
53+
+ 缺点
54+
55+
+ 在封装器栈中删除特定封装器比较困难
56+
+ 实现行为不受装饰栈顺序影响的装饰比较困难
57+
+ 各层的初始化配置代码看上去可能会很糟糕
58+

Design Mode/src/decorating_mode.go

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,49 @@
11
package main
22

3-
func main() {
3+
import (
4+
"fmt"
5+
)
46

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())
517
}
618

719
//零件接口
820
type IPizza interface {
921
getPrice() int
1022
}
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+
}

0 commit comments

Comments
 (0)