装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。
这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。示例参考大话设计模式中代码
class Person { 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) { this.component = component; } public override void Show() { if (Equals(component!=null)) { component.Show();; } } } class TShirts:Finery { public override void Show() { Console.Write("TShirts "); base.Show(); } } class Trouser : Finery { public override void Show() { Console.Write("Trouser "); base.Show(); } }
static void Main(string[] args) { Person person=new Person("张三"); person.Show(); TShirts tShirts=new TShirts(); Trouser trouser=new Trouser(); tShirts.Decorate(person); tShirts.Show(); trouser.Decorate(person); trouser.Show(); Console.ReadLine(); }
输出结果:
装扮的张三
TShirts Trouser
给张三穿上TShirt,Trouser,并使TShirt,Trouser显示出来。原书中代码只有最后一个Show()是不会显示TShirt的,除非将每次装饰使用列表保存下来。