装饰模式(Decorator),动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。

以下是装饰模式的例子:

具体代码:
Person.cs
1 namespace DecorativePattern
2 {
3 class Person
4 {
5 public Person()
6 { }
7 private string name;
8 public Person(string name)
9 {
10 this.name = name;
11 }
12 public virtual void Show()
13 {
14 Console.WriteLine("装扮的{0}", name);
15 }
16 }
17 }
Finery.cs
1 namespace DecorativePattern
2 {
3 //服饰类
4 class Finery : Person
5 {
6 protected Person component;
7
8 //打扮
9 public void Decorate(Person component)
10 {
11 this.component = component;
12 }
13
14 public override void Show()
15 {
16 if (component != null)
17 {
18 component.Show();
19 }
20 }
21 }
22 }
Program.cs
1 namespace DecorativePattern
2 {
3 class Program
4 {
5 static void Main(string[] args)
6 {
7 Person xc = new Person("小菜");
8 //1
9 Console.WriteLine("\n第一种装扮:");
10
11 Sneakers sneaker = new Sneakers();
12 BigTrouser bigTrouser = new BigTrouser();
13 Tshirts tshirts = new Tshirts();
14
15 //装饰过程
16 sneaker.Decorate(xc);
17 bigTrouser.Decorate(sneaker);
18 tshirts.Decorate(bigTrouser);
19 tshirts.Show();
20 //2
21 Console.WriteLine("\n第二种装扮:");
22
23 LeatherShoes leatherShoes = new LeatherShoes();
24 Tie tie = new Tie();
25 Suit suit = new Suit();
26
27 //装饰过程
28 leatherShoes.Decorate(xc);
29 tie.Decorate(leatherShoes);
30 suit.Decorate(tie);
31 suit.Show();
32
33 Console.Read();
34 }
35 }
36
37 class Tshirts : Finery
38 {
39 public override void Show()
40 {
41 Console.Write("大T恤");
42 base.Show();
43 }
44 }
45
46 class BigTrouser:Finery
47 {
48 public override void Show()
49 {
50 Console.Write("垮裤");
51 base.Show();
52 }
53
54 }
55
56 class Sneakers : Finery
57 {
58 public override void Show()
59 {
60 Console.Write("破球鞋 ");
61 base.Show();
62 }
63 }
64
65 class Suit : Finery
66 {
67 public override void Show()
68 {
69 Console.Write("西装 ");
70 base.Show();
71 }
72 }
73
74 class Tie : Finery
75 {
76 public override void Show()
77 {
78 Console.Write("领带 ");
79 base.Show();
80 }
81 }
82
83 class LeatherShoes : Finery
84 {
85 public override void Show()
86 {
87 Console.Write("皮鞋 ");
88 base.Show();
89 }
90 }
91 }
1234

被折叠的 条评论
为什么被折叠?



