设计模式(三)——装饰模式

来源:互联网 发布:app one是什么软件 编辑:程序博客网 时间:2024/06/06 01:06

装饰模式(Decorator)

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


代码

我们来实现一个简单的个人形象系统来阐述装饰模式:
(注意:如果只有一个ConcreteComponent类而没有抽象的Component类,那么Decorator类可以是ConcreteComponent的一个子类。同样道理,如果只有一个ConcreteDecorator类,那么就没有必要建立一个单独的Decorator类,而可一个把Decorator和ConcreteDecorator的责任合并成一个类。所以我们这里就没有必要有Component类了,直接让服饰类Decorator继承人类ConcreteComponent就可。)
1.我们先来定义一个Person的基类,用于装饰的对象,代码如下:

人类

using System;namespace Decorator{//人类(ConcreteComponent)public class Person{//名字private string name;public Person (){}public Person(string name){this.name = name;}//展示public virtual void Show(){Console.WriteLine ("装扮的{0}", name);}}}
2.装饰类的基类,代码如下:

装饰类的基类

using System;namespace Decorator{//服饰类(Decorator)public class Finery:Person{//被装饰的人protected Person person;//打扮public void Decorate(Person person){this.person = person;}public override void Show(){if (person != null) {person.Show ();}}}}
3.具体的装饰类,代码如下:

T桖类

using System;namespace Decorator{//T桖类(ConcreteDecorator)public class TShirts:Finery{public override void Show(){Console.Write ("大T桖");base.Show ();}}}

大垮裤类

using System;namespace Decorator{//大垮裤类(ConcreteDecorator)public class BigTrouser:Finery{public override void Show(){Console.Write ("大垮裤");base.Show ();}}}

球鞋类

using System;namespace Decorator{//球鞋类(ConcreteDecorator)public class Sneakers:Finery{public override void Show(){Console.Write ("大T桖");base.Show ();}}}

西装类

using System;namespace Decorator{//西装类(ConcreteDecorator)public class Suit:Finery{public override void Show(){Console.Write ("西装");base.Show ();}}}

领带类

using System;namespace Decorator{//领带类(ConcreteDecorator)public class Tie:Finery{public override void Show(){Console.Write ("领带");base.Show ();}}}

皮鞋类

using System;namespace Decorator{//皮鞋类(ConcreteDecorator)public class LeatherShoes:Finery{public override void Show(){Console.Write ("皮鞋");base.Show ();}}}
4.客户端代码,如下:
using System;namespace Decorator{class MainClass{public static void Main (string[] args){Person person = new Person ("小三");Console.WriteLine ("\n第一种装扮:");Sneakers sneaker = new Sneakers ();BigTrouser bigTrouser = new BigTrouser ();TShirts tShirts = new TShirts ();sneaker.Decorate (person);bigTrouser.Decorate (sneaker);tShirts.Decorate (bigTrouser);tShirts.Show ();Console.WriteLine ("\n第二种装扮:");LeatherShoes leatherShoes = new LeatherShoes ();Tie tie = new Tie ();Suit suit = new Suit ();leatherShoes.Decorate (person);tie.Decorate (leatherShoes);suit.Decorate (tie);suit.Show ();}}}
5.运行结果:

UML图


源码下载地址http://blog.csdn.net/maybehelios/article/details/2038685