”装饰“想到的就是人的服饰、一个物体的改造等。那么如果放在代码中时如何装饰的呢?
先要有一个被装饰的物体,拿人做例子的话,就先要有一个人的类。
private string name; public Person (string name) { this.name = name; } public void Show() { Console.WriteLine("装扮的{0}", name); }
有了人之后还要有一个卖衣服的地方。
abstract class Finery { public abstract void Show(); }
服装店里面还有各种衣服的类型
class TShirts : Finery { public override void Show() { Console.Write("大T恤"); } } class BigTrouser : Finery { public override void Show() { Console.Write("跨裤"); } } class Sneakers : Finery { public override void Show() { Console.Write("破球鞋"); } } class Suit : Finery { public override void Show() { Console.Write("西装"); } } class LeatherShoes : Finery { public override void Show() { Console.Write("皮鞋"); } } class Tie : Finery { public override void Show() { Console.Write("领带"); } }
客户端
Person xc = new Person("小菜"); Console.WriteLine("\n 第一种装饰:"); Finery dtx = new TShirts(); Finery dkk = new BigTrouser(); Finery pqx = new Sneakers(); dtx.Show(); dkk.Show(); xc.Show(); Console.WriteLine("\n第二种装扮:"); Finery xz = new Suit(); Finery ld = new Tie(); Finery px = new LeatherShoes(); xz.Show(); ld.Show(); px.Show(); xc.Show(); Console.Read();
可以发现在客户端有很多的重复,这需要进行修改。
装饰模式
public Person() { } private string name; public Person (string name) { this.name = name; } public virtual void Show() { Console.WriteLine("装扮的{0}", name); }
class Finery :Person { protected Person component; //打扮 public void Decorate(Person component)//Decorate点缀的意思,component组成 { this.component = component; } public override void Show() { if (component!=null) { component.Show(); } } }
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 LeatherShoes : Finery { public override void Show() { Console.Write("皮鞋"); base.Show(); } } class Tie : Finery { public override void Show() { Console.Write("领带"); base.Show(); } }
客户端
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(); }