小菜要去见娇娇了,穿什么好呢?下面就让我们学习一下装饰模式吧!
装饰模式:动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更灵活.
装饰模式包括:抽象结构(Component)、具体结构(ConcreateCompinent)、装饰(Decrator)、具体装饰(ConcreteDecorator)
装饰模式结构图如下:
下面来看看小菜究竟想打扮成什么样子去见娇娇吧!
class Person //Person类(ConcreteComponent) { public Person() { } private string name; public Person(string name) { this.name = name; } public virtual void Show() { Console.WriteLine("装扮的{0}", name); } }
class Finery:Person //服饰类(Decorator) { protected Person component; //打扮 public void Decorate(Person component) { this.component = component; } public override void Show() { if (component != null) { component.Show(); } }
//具体服饰类(大T恤) class TShirts:Finery { public override void Show() { Console.Write("大T恤 "); base.Show(); } }
//具体服饰类(垮裤) class BigTrouser:Finery { public override void Show() { Console.Write("垮裤 "); base.Show(); } }
//具体服饰类(破球鞋) class Sneakers:Finery { public override void Show() { Console.Write("破球鞋 "); base.Show(); } }
//具体服饰类(西装) class Suit:Finery { public override void Show() { Console.Write("西装 "); base.Show(); } }
//具体服饰类(领带) class Tie:Finery { public override void Show() { Console.Write("领带 "); base.Show(); } }
//具体服饰类(皮鞋) class LeatherShoes:Finery { public override void Show() { Console.Write("皮鞋 "); base.Show(); } }
class Program //客户端代码 { static void Main(string[] args) { Person xc = new Person("小菜"); Console.WriteLine("\n第一种装扮:"); Sneakers pqx = new Sneakers(); TShirts dtx = new TShirts(); BigTrouser kk = new BigTrouser(); pqx.Decorate(xc); dtx.Decorate(pqx); kk.Decorate(dtx); kk.Show(); Console.WriteLine("\n第二种装扮"); Suit xz = new Suit(); Tie ld = new Tie(); LeatherShoes px = new LeatherShoes(); xz.Decorate(xc); ld.Decorate(xz); px.Decorate(ld); px.Show(); Console.Read(); }结果显示
当系统需要新功能的时候,是向旧的类中添加新的代码。这些新加的代码通透擦灰姑娘装饰了原有类的核心职责或主要行为。
每一种模式都有它的优缺点:装饰模式最大的优点就是把类中的装饰功能从类中搬移出去,这样可以简化原有的类,有效的把类的核心职责和装饰功能区分开了,而且可以去除相关类中重复的装饰逻辑。
原文:http://blog.csdn.net/u010785685/article/details/22805919