2013年11月12日 星期二

POSD學習筆記(7)-Strategy Pattern

沒有時間,先用學校投影片的圖擋一下,之後再自己畫

例:
Client new Context工具,然後呼叫Context.ContextInterface(Algorithm Type)
接著Context會讓Strategy去依照給的Algorithm Type去呼叫對應的ConcreteStrategy然後回傳給Context,Context再給Client。

好處:
  1. 同類型的演算法可歸為同一類
  2. 可以不用switch/if去選擇演算法











以下為轉載,轉自:http://www.cnblogs.com/oomusou/archive/2007/03/26/687727.html

Remark:
strategy和template method目的相同,皆對『新需求』的不同演算法提供『擴充』的機制,但手法卻不同,strategy採用object的方式,利用delegation改變演算法,而template method則採用class的繼承方式來改變演算法,也因為strategy採用object方式,所以有run-time改變的可能,但template method採class手法,所以無法run-time改變。

GoF的原文如下:
Template methods use inheritance to vary part of an algorithm. Strategies use delegation to vary the entire algorithm.




沒有留言:

張貼留言