1. 程式人生 > >設計模式 - 裝飾模式

設計模式 - 裝飾模式

void 去除 ora () override collect fin app names

裝飾模式(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 }

裝飾模式是為自己已有功能動態添加更多功能的一種方式。

優點:把類中裝飾功能從類中搬移出去,這樣可以簡化原有的類。這樣可以有效的把核心功能和裝飾功能區分開了,而且可以去除相關類中重復的裝飾邏輯。

設計模式 - 裝飾模式