装饰者模式,所谓装饰者模式,就是能够自由动态扩展功能,装饰者和被装饰折拥有同一个超类,比如System.IO系统,
我个人认为的装饰者模式就是 (((被装饰者)装饰者+)+装饰者)+装饰者.....无穷无尽的扩展.....
该模式也符合设计模式原则:
开-闭原则对扩展开放,对修改关闭.
优先使用组合而非继承,不过这里继承的目的不是为了获得行为而是为了匹配类型
以下以咖啡饮料为例解释装饰者模式:
1
/**//// <summary>
2
/// 被装饰者超类
3
/// </summary>
4
public abstract class super
5
{
6
public abstract void write();
7
}
8
/**//// <summary>
9
/// 装饰者继承超类
10
/// </summary>
11
public abstract class Component:super
12
{
13
public abstract void getTotal();
14
}
15
16
/**//// <summary>
17
/// 被装饰者
18
/// </summary>
19
public class decker:super
20
{
21
string name;
22
int price;
23
24
public decker(string name, int price)
25
{
26
this.name = name;
27
this.price = price;
28
}
29
public override void write()
30
{
31
Console.WriteLine(string.Format(@"我是被装饰者:{0},我的价格是{1}", name, Price));
32
}
33
}
34
/**//// <summary>
35
/// 装饰者
36
/// </summary>
37
public class decoratee : Component
38
{
39
string name;
40
int price;
41
super s;
42
43
public decoratee(string name, int price,super s)
44
{
45
this.name = name;
46
this.price = price;
47
this.s = s;
48
}
49
public override void getTotal()
50
{
51
write();
52
}
53
public override void write()
54
{
55
s.write();
56
//自定义方法
57
Console.WriteLine(string.Format(@"我是装饰者:{0},我的价格是{1}", name, price));
58
}
59
}
60
61
class Program
62
{
63
static void Main(string[] args)
64
{
65
//定义被装饰者
66
super d_1 = new decker("卡布奇诺", 15);
67
//定义被装饰者
68
Component dec_1 = new decoratee("糖", 3, d_1);
69
//循环包装
70
dec_1 = new decoratee("吸管", 2, dec_1);
71
dec_1 = new decoratee("大杯子", 2, dec_1);
72
dec_1 = new decoratee("精美包装盒", 4, dec_1);
73
dec_1 = new decoratee("牛奶", 1, dec_1);
74
75
//统计
76
dec_1.getTotal();
77
Console.ReadKey();
78
}
79
}


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

运行结果: