装饰模式(Decorator):动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
就以穿衣服为例,无论是鞋子、领带、披风都是对人的装饰。
定义一个人类
<strong><span style="font-family:KaiTi_GB2312;"> class Person
{
public Person()
{ }
private string name;
public Person(string name)
{
this.name = name;
}
public virtual void Show()
{
Console.WriteLine("装扮的{0}",name );
}
}</span></strong>
服饰类
<strong><span style="font-family:KaiTi_GB2312;"> class Finery :Person
{
protected Person component;
//打扮
public void Decorate(Person component)
{
this.component = component;
}
public override void Show()
{
if (component !=null )
{
component.Show();
}
}
}</span></strong>
各衣服的类
<strong><span style="font-family:KaiTi_GB2312;">//垮裤
class BigTrouser : Finery
{
public override void Show()
{
Console.Write("垮裤");
base.Show();
}
}</span></strong>
</pre><pre name="code" class="csharp"><strong><span style="font-family:KaiTi_GB2312;">//皮鞋 </span></strong>
<strong><span style="font-family:KaiTi_GB2312;">class LeatherShoes : Finery { public override void Show() { Console.Write("皮鞋"); base.Show(); } }</span></strong>
</pre><pre name="code" class="csharp"><strong><span style="font-family:KaiTi_GB2312;"> //破球鞋 class Sneakers : Finery { public override void Show() { Console.Write("破球鞋"); base.Show(); } }</span></strong>
</pre><pre name="code" class="csharp"><strong><span style="font-family:KaiTi_GB2312;">//西装 </span></strong>
<strong><span style="font-family:KaiTi_GB2312;">class Suit : Finery { public override void Show() { Console.Write("西装"); base.Show(); } }</span></strong>
</pre><pre name="code" class="csharp"><strong><span style="font-family:KaiTi_GB2312;">//领带</span></strong>
<strong><span style="font-family:KaiTi_GB2312;"> class Tie : Finery { public override void Show() { Console.Write("领带"); base.Show(); } }</span></strong>
</pre><pre name="code" class="csharp"><strong><span style="font-family:KaiTi_GB2312;">//大T恤</span></strong>
<strong><span style="font-family:KaiTi_GB2312;">class Tshirts :Finery { public override void Show() { Console.Write("大T恤"); base.Show(); } }</span></strong>
客户端代码
<strong><span style="font-family:KaiTi_GB2312;"> class Program
{
static void Main(string[] args)
{
Person xc = new Person("小菜");
Console.WriteLine("\n第一种装扮:");
Sneakers pqx = new Sneakers();
BigTrouser kk = new BigTrouser();
Tshirts dtx = new Tshirts();
pqx.Decorate(xc);
kk.Decorate(pqx );
dtx.Decorate(kk);
dtx.Show();
Console.WriteLine("\n第二种装扮");
LeatherShoes px = new LeatherShoes();
Tie ld = new Tie();
Suit xz = new Suit();
px.Decorate(xc);
ld.Decorate(px );
xz.Decorate(ld );
xz.Show();
Console.Read();
}
}</span></strong>
效果:
装饰模式把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,当需要只想特殊行为时,客户代码就可以在运行时根据需要有选择地、按顺序地使用装饰功能包装对象。
我理解的是,我们每个人都是一个客户端,我们的每一件衣服就是一个已经包装好了的类,当我们使用装饰模式时,就相当于我们在打扮自己,我们选择穿哪一件衣服,穿衣服的顺序等等。