策略模式(Strategy Pattern)根據不同的環境條件,選擇最適當演算法(一組同性質算法)來使用。
the strategy pattern (also known as the policy pattern) is a particular software design pattern, whereby algorithms can be selected at runtime. Formally speaking, the strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.[1]
策略模式算日常開發滿常使用模式,尤其是做專案時,使用者常常會開出這樣子需求, 根據{A -> A_activity, B -> B_activity, C -> C_activity...}對於這些{A, B, C...}_activity幾乎非常相似應該也可說是同性質活動,同時還要求日後可擴充。
最常見的範例 每一種不同產品{book, nb, pc...}類型有不同折扣數;不同的壓縮{zip, rar, gz...}有不同的壓縮算法;不同的檔案格式{doc, exe, xls...}有不同的處理邏輯等。
所以可定義有一組同性質算法,並將每種算法封裝起來,讓它們可根據不同的條件來互換使用。
策略模式結構:
java程式碼
[code lang="java"] //Strategy Interface public interface CompressionStrategy { public void compressFiles(File []files); } public class ZipCompressionStrategy implements CompressionStrategy { public void compressFiles(File []files) { //using ZIP approach } } public class RarCompressionStrategy implements CompressionStrategy { public void compressFiles(File []files) { //using RAR approach } } public class CompressionContext { private CompressionStrategy strategy; //this can be set at runtime by the application preferences public void setCompressionStrategy(CompressionStrategy strategy) { this.strategy = strategy; } //use the strategy public void createArchive(File []files) { strategy.compressFiles(files); } } //test public class Client { public static void main(String[] args) { CompressionContext ctx = new CompressionContext(); ctx.setCompressionStrategy(new ZipCompressionStrategy()); //get a list of files ... ctx.createArchive(fileList); } } [/code]雖然已經寫出Strategy Pattern 模式,但它不完美。主要缺點必須瞭解每個算法+Context才能使用,比較好方式還是將 CompressionContext封裝成 CompressionFactory 或者 CompressionService,以利開發者開發使用。
策略模式在開發中常常遇見變形也很多,只能靠多想多重構來建立本能。
參考
http://java.dzone.com/articles/design-patterns-strategy?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+zones%2Farchitects+(Architects+Zone)
No comments:
Post a Comment