设计模式笔记4 装饰模式

1.1  定义

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

 

1.2  类图

1.3  代码

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace 装饰模式
 8 {
 9     class Person
10     {
11         private string name;
12         public Person() { }
13         public Person(string name)
14         {
15             this.name = name;
16         }
17 
18         public virtual void Show()
19         {
20             Console.WriteLine("装扮的{0}", this.name);
21         }
22     }
23     // 服饰类
24     class Finery : Person
25     {
26         protected Person component;
27 
28         // 打扮
29         public void Decorate(Person component)
30         {
31             this.component = component;
32         }
33 
34         public override void Show()
35         {
36             if (component!=null)
37             {
38                 component.Show();
39             }
40         }
41 
42 
43 
44     }
45 
46     // 具体服饰类
47     class TShirt : Finery
48     {
49         public override void Show()
50         {
51             Console.WriteLine("大T恤");
52             base.Show();
53         }    
54     }
55 
56     // 牛仔裤
57     class Jeans : Finery
58     {
59         public override void Show()
60         {
61             Console.WriteLine("牛仔裤");
62             base.Show();
63         }
64     }
65 
66 
67     class Shoes : Finery
68     {
69         public override void Show()
70         {
71             Console.WriteLine("破球鞋");
72             base.Show();
73         }
74     }
75 
76 }
View Code

 

调用

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace 装饰模式
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             Person p = new Person("大头");
14 
15 
16             TShirt t = new TShirt();
17             Jeans j = new Jeans();
18             Shoes s = new Shoes();
19 
20             t.Decorate(p);
21             j.Decorate(t);
22             s.Decorate(j);
23 
24             s.Show();
25 
26         }
27     }
28 }
View Code

 

 

1.4  总结

 

   装饰模式就是为已有功能动态地添加更多功能的一种方式。

  当我们系统需要更新功能时,给原有的类添加装饰模式,就可以给主类添加新的方法和字段。

posted @ 2014-12-02 23:22  AfreadHuang  阅读(146)  评论(0编辑  收藏  举报