装饰模式:当系统需要新的功能的时候,是向旧的类中添加新的代码。这样新的代码通常装饰了原有类的核心职责或者主要行为。
优点:把类中的装饰功能从类中搬移去除,这样可以简化原有的类。有效地把类的核心职责和装饰功能分开。而且可以去除相关类中重复的装饰逻辑。
装饰模式实现穿衣服功能:
class Program { static void Main(string[] args) { Person cw = new Person("cw"); TShirts t = new TShirts(); BigTrouser b = new BigTrouser(); t.Decorate(cw); b.Decorate(t); b.Show(); Console.ReadKey(); } public class Person { public Person() { } private string _name; public Person(string name) { _name = name; } public virtual void Show() { Console.Write("装扮的{0}",_name); } } public class Finery:Person { protected Person component; public void Decorate(Person component) { this.component = component; } public override void Show() { if(component!=null) { component.Show(); } } } public class TShirts:Finery { public override void Show() { base.Show(); Console.Write("大T恤3"); } } public class BigTrouser:Finery { public override void Show() { base.Show(); Console.Write("垮裤"); } }
代码运行结果: