Decorator模式
概述
Decorator模式(装饰模式):装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案,提供比继承更多的灵活性。动态给一个对象增加功能,这些功能可以再动态的撤消。增加由一些基本功能的排列组合而产生的非常大量的功能。
设计
给一个对象添加职责,可以直接修改这个对象,但是这样就变得很危险。本着最大限度不修改原有代码的编码指导思想,应该对这个对象进行包装,再赋予新的对象额外的职责。就如一个步兵有杀伤敌人的功能,再把他装进战车,就额外拥有移动快、防御强的功能了。
实现
UML图:
示例代码为:
1
using System;
2
3
namespace Example
4
{
5
/// <summary>
6
/// 示例
7
/// </summary>
8
class Example
9
{
10
/// <summary>
11
/// 应用程序的主入口点。
12
/// </summary>
13
[STAThread]
14
static void Main(string[] args)
15
{
16
//张三今天的计划
17
Console.WriteLine( "张三今天的计划:" ) ;
18
Action ZhangSan = new Eat( new Sleep( new Sport( new Action() ) ) ) ;
19
ZhangSan.Act() ;
20
//李四今天的计划
21
Console.WriteLine( "李四今天的计划:" ) ;
22
Action LiSi = new Sport( new Eat( new Sleep( new Action() ) ) ) ;
23
LiSi.Act() ;
24
}
25
/// <summary>
26
/// 主要的功能:工作
27
/// </summary>
28
public class Action
29
{
30
public virtual void Act()
31
{
32
Console.WriteLine( "工作……" ) ;
33
}
34
}
35
/// <summary>
36
/// 使用Decorator模式,增加额外功能:吃饭
37
/// </summary>
38
public class Eat : Action
39
{
40
private Action action = null ;
41
42
public Eat( Action a )
43
{
44
action = a ;
45
}
46
public void EatRice()
47
{
48
Console.WriteLine( "吃饭……" ) ;
49
}
50
public override void Act()
51
{
52
this.EatRice() ;
53
action.Act() ;
54
}
55
}
56
/// <summary>
57
/// 使用Decorator模式,增加额外功能:睡觉
58
/// </summary>
59
public class Sleep : Action
60
{
61
private Action action = null ;
62
63
public Sleep( Action a )
64
{
65
action = a ;
66
}
67
public void Sleeping()
68
{
69
Console.WriteLine( "睡觉……" ) ;
70
}
71
public override void Act()
72
{
73
this.Sleeping() ;
74
action.Act() ;
75
}
76
}
77
/// <summary>
78
/// 使用Decorator模式,增加额外功能:运动
79
/// </summary>
80
public class Sport : Action
81
{
82
private Action action = null ;
83
84
public Sport( Action a )
85
{
86
action = a ;
87
}
88
public void Sporting()
89
{
90
Console.WriteLine( "运动……" ) ;
91
}
92
public override void Act()
93
{
94
this.Sporting() ;
95
action.Act() ;
96
}
97
}
98
}
99
}
100

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

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100
