2016年4月7日 星期四

設計模式二:策略模式(Strategy)

如果說多型是為了讓未來的物件可以使用現有的演算法,那麼策略模式就是讓物件固定而演算法可以更換。

例如檔案物件的排序,可以依據檔名、時間、種類、大小等等。排序演算法雖不同,但皆是針對檔案系統設計的。而使用者可以依需求選擇演算法、增減演算法而達到系統的靈活性。

這種設計對測試、維護、擴展程式都有顯而易見的好處。

《head first design pattern》介紹本模式時,也順便強調了「多用合成、少用繼承」的觀念。以上面的例子來說:一個檔案清單可以擁有(即合成)一個sorting的介面,而實作這個介面的可以是sortingByDate, sortingByFileSize, sortingByName等等。

而策略模式就是依據需求產生實際的物件再合成到檔案清單中。另一種用法就是繼承檔案清單後,根據需求override一個function以產生實作sorting介面的物件。如此一來,就只需要實作不同的sorting行為,就可以有不同能力的檔案清單。

"The Strategy design pattern - Problem, Solution, and Applicability". w3sDesign.com的定義是:the strategy pattern is a behavioral software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use.

沒有留言:

張貼留言