首页 > 代码库 > 装饰模式

装饰模式

1. 简介

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

2. 程序示例

 1 class Program 2     { 3         static void Main(string[] args) 4         { 5             Person huoaa = new Person("霍啊啊"); 6  7             Sneakers pqx = new Sneakers(); 8             BigTrouser kk = new BigTrouser(); 9             TShirts dtx = new TShirts();10 11             pqx.Decorate(huoaa);12             kk.Decorate(pqx);13             dtx.Decorate(kk);14             dtx.Show();15         }16     }17 18     //Person类(ConcreteComponent)19     class Person20     {21         public Person()22         { }23 24         private string name;25 26         public Person(string name)27         {28             this.name = name;29         }30 31         public virtual void Show()32         {33             Console.WriteLine("装扮的{0}", name);34         }35     }36 37     //服饰类(Decorator)38     class Finery : Person39     {40         protected Person component;41 42         //打扮43         public void Decorate(Person component)44         {45             this.component = component;46         }47 48         public override void Show()49         {50             if (component != null)51             {52                 component.Show();53             }54         }55     }56 57     //具体服饰类(ConcreteDecorator)58 59     class TShirts : Finery60     {61         public override void Show()62         {63             Console.Write("大T恤 ");64             base.Show();65         }66     }67 68     class BigTrouser : Finery69     {70         public override void Show()71         {72             Console.Write("垮裤 ");73             base.Show();74         }75     }76 77     class Sneakers : Finery78     {79         public override void Show()80         {81             Console.Write("破球鞋 ");82             base.Show();83         }84     }

 

装饰模式