装饰模式(Decorator):
动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace ConsoleApplication1 7 { 8 class Person 9 { 10 private string name; 11 12 public Person() 13 { } 14 15 public Person(string name) 16 { 17 this.name = name; 18 } 19 20 public virtual void Show() 21 { 22 Console.Write(" Decorated " + this.name); 23 } 24 } 25 26 class Finery: Person 27 { 28 private Person person; 29 30 public void SetDecoration(Person person) 31 { 32 this.person = person; 33 } 34 35 public override void Show() 36 { 37 if(this.person != null) 38 { 39 this.person.Show(); 40 } 41 } 42 } 43 44 class Sneaker: Finery 45 { 46 public override void Show() 47 { 48 Console.Write(" Sneaker "); 49 50 base.Show(); 51 } 52 } 53 54 class Jeans : Finery 55 { 56 public override void Show() 57 { 58 Console.Write(" Jeans "); 59 60 base.Show(); 61 } 62 } 63 64 class WhiteTshirt : Finery 65 { 66 public override void Show() 67 { 68 Console.Write(" White Tshirt "); 69 70 base.Show(); 71 } 72 } 73 74 class Program 75 { 76 static void Main(string[] args) 77 { 78 Person jim = new Person("Jim"); 79 Sneaker sneaker = new Sneaker(); 80 Jeans jeans = new Jeans(); 81 WhiteTshirt whiteTshirt = new WhiteTshirt(); 82 83 sneaker.SetDecoration(jim); 84 jeans.SetDecoration(sneaker); 85 whiteTshirt.SetDecoration(jeans); 86 87 whiteTshirt.Show(); 88 89 Console.ReadLine(); 90 } 91 } 92 }
装饰模式是为自己已有功能动态添加更多功能的一种方式。
优点:把类中装饰功能从类中搬移出去,这样可以简化原有的类。这样可以有效的把核心功能和装饰功能区分开了,而且可以去除相关类中重复的装饰逻辑。