-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathDecoratorPattern.md
79 lines (58 loc) · 1.4 KB
/
DecoratorPattern.md
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# 装饰模式
动态地给一个对象增加一些额外的职责,就拓展对象功能来说,装饰模式比生成子类的方式更为灵活。
一般的,我们为了扩展一个类经常使用继承方式实现,由于继承为类引入静态特征,并且随着扩展功能的增多,子类会很膨胀。
## 样例

```swift
protocol Shape {
func draw()
}
class Rectangle: Shape {
func draw() {
print("形状: 矩形")
}
}
class Circle: Shape {
func draw() {
print("形状:圆")
}
}
class ShapeDecorator: Shape {
let decoratedShape: Shape
init(shape: Shape) {
self.decoratedShape = shape
}
func draw() {
decoratedShape.draw()
}
}
class RedShapeDecorator: ShapeDecorator {
override func draw() {
super.draw()
setRedBorder()
}
func setRedBorder() {
print("边框的颜色:红色")
}
}
let cirle = Circle()
let redCircle = RedShapeDecorator(shape: Circle())
let redRectangle = RedShapeDecorator(shape: Rectangle())
print("无边框的圆")
cirle.draw()
print("\n红色边框的圆")
redCircle.draw()
print("\n红色边框的矩形")
redRectangle.draw()
```
结果输出:
```sh
无边框的圆
形状:圆
红色边框的圆
形状:圆
边框的颜色:红色
红色边框的矩形
形状: 矩形
边框的颜色:红色
```