策略模式:定義了一系列的算法,並將每一個算法封裝起來,而且使它們還可以相互替換。策略模式讓算法獨立於使用它的客戶而獨立變化; 使用的關鍵點是面對對象、面向接口編程。舉個例子,以武士可以不斷更換武器為例子背景: 策略模式實現步驟一:定義抽象策略類
1 interface IStrategy 2 { 3 void fighting(); 4 }
策略模式實現步驟二:實現具體策略類
1 class Bow:IStrategy 2 { 3 public void fighting() 4 { 5 Console.WriteLine("向敵人放冷箭中……"); 6 } 7 }
1 class Knife:IStrategy 2 { 3 public void fighting() 4 { 5 Console.WriteLine("使用刀作為武器…"); 6 } 7 }
1 class Cannon:IStrategy 2 { 3 public void fighting() 4 { 5 Console.WriteLine("加農炮轟擊敵人中……"); 6 } 7 }
策略模式實現步驟三:定義環境類
1 class Context 2 { 3 private IStrategy _strategy; 4 public Context(IStrategy s) 5 { 6 this._strategy = s; 7 } 8 public void fighting() 9 { 10 this._strategy.fighting(); 11 } 12 }
//調用
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 Context context; 6 context = new Context(new Knife()); 7 Console.WriteLine("選擇武器為刀:"); 8 context.fighting(); 9 Console.WriteLine(); 10 context = new Context(new Bow()); 11 Console.WriteLine("選擇武器為弓:"); 12 context.fighting(); 13 Console.WriteLine(); 14 context = new Context(new Cannon()); 15 Console.WriteLine("選擇武器為加農炮:"); 16 context.fighting(); 17 Console.WriteLine(); 18 } 19 }
適配器模式:是在想使用一個已經存在的類,但是他的接口並不符合要求,因為在編碼過程中要遵循對擴展開放,對修改關閉的原則,所以不能對原有的類進行修改,這時便需要使用適配器模式,將原有的類適配成自己需要的形式。有類適配器和對象適配器兩種適配器。舉個簡單的例子,以原本有一只神鹿只會快速跑,現在讓它也會飛為背景,便能明白怎樣使用了: 適配器模式實現步驟一:確定目標接口
1 interface ITarget 2 { 3 void run(); 4 void fly(); 5 }
適配器模式實現步驟二:確定被適配者
1 class Deer 2 { 3 public void run() 4 { 5 Console.WriteLine("我是一只神鹿,可帶你游走四處。"); 6 } 7 }
適配器模式實現步驟三:創建適配器(類適配器)
1 class classAdapter : Deer,ITarget //注意,這是采用繼承的方式 2 { 3 public void fly() 4 { 5 Console.WriteLine("哇啊哦,我可以飛了!!"); 6 } 7 }
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 ITarget flyDeer = new classAdapter(); 6 flyDeer.run(); 7 flyDeer.fly(); 8 } 9 }
適配器模式實現步驟三:創建適配器(對象適配器)
1 class objectAdapter:ITarget 2 { 3 private Deer deer; //注意,這里是將目標作為適配器的一個成員 4 public objectAdapter(Deer d) 5 { 6 this.deer = d; 7 } 8 public void run() 9 { 10 deer.run(); 11 } 12 public void fly() 13 { 14 Console.WriteLine("哇啊哦,我一樣可以飛!!"); 15 } 16 }
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 ITarget flyDeer = new objectAdapter(new Deer()); 6 flyDeer.run(); 7 flyDeer.fly(); 8 } 9 }
策略模式優於適配器模式:
1.首先很大程度上簡化了我們的代碼。
2.降低了我們程序代碼的耦合度,而低耦合正是面向對象的重要優點。
