设计模式之装饰器模式

装饰器模式:允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有类的一个包装。这种模式创建一个装饰类,用来包装原有的类。并在保证类方法签名完整性的前提下,提供了额外的功能。

介绍

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

使用场景:扩展一个类的功能,动态增加功能,动态撤销。

如何使用:在不想增加很多子类的情况下扩展类。

关键代码:1.Component1类充当抽象角色,不应该具体实现。2.修饰类应用和继承component类,具体扩展类重写父类方法。

优点:装饰类和被装饰类可以独立发展,不会相互耦合,装饰器模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。

缺点:多层装饰比较复杂。

实例

 1 class Person
 2     {
 3         private String m_name;
 4 
 5         public Person()
 6         { 
 7         
 8         }
 9         public Person(String name)
10         {
11             m_name = name;
12         }
13 
14         public virtual void Show()
15         {
16             Console.WriteLine("装扮的{0}",m_name);
17         }
18     }
19 
20 class Finery:Person
21     {
22         protected Person m_comonent;
23 
24         public void Decorate(Person comonent)
25         {
26             m_comonent = comonent;
27         }
28 
29         public override void Show()
30         {
31             if (m_comonent != null)
32             {
33                 m_comonent.Show();
34             }
35         }
36     }
37 
38     class TShirts : Finery
39     {
40         public override void Show()
41         {
42             Console.WriteLine("大T恤");
43             base.Show();
44         }
45     }
46 
47     class BigTrouser : Finery
48     {
49         public override void Show()
50         {
51             Console.WriteLine("垮裤");
52             base.Show();
53         }
54     }
55 
56     class Sneaker : Finery
57     {
58         public override void Show()
59         {
60             Console.WriteLine("运动鞋");
61             base.Show();
62         }
63     }
64 
65 static void Main(string[] args)
66         {
67             Person person = new Person("hanchen");
68             Console.WriteLine("第一种装扮");
69             Sneaker sneaker = new Sneaker();
70             BigTrouser bigTrouser = new BigTrouser();
71             TShirts tShirts = new TShirts();
72 
73             sneaker.Decorate(person);
74             bigTrouser.Decorate(sneaker);
75             tShirts.Decorate(bigTrouser);
76             tShirts.Show();
77 
78             Console.ReadLine() ;
79         }
原文地址:https://www.cnblogs.com/mohanchen/p/9588172.html