6/29/2011

Build Strategy Pattern

繼上一篇Strategy Pattern 討論到程式碼並不完美,主要缺失必須要瞭解每個算法與Context才能自在使用。比較好處理方式可將Context包裝成CompressionFactory或CompressionService方便其他人呼叫使用,但如何去建構?

自行撰寫雖然也不是問題,但似乎太浪費時間在處理此細節。

Tapestry IoC framework提供 StrategyBuilder 容易建立Strategy Pattern

A service implementation builder that operates around a StrategyRegistry, implementing a version of the Gang of Four Strategy pattern. The constructed service is configured with a number of adapters (that implement the same service interface). Method invocations on the service are routed to one of the adapters.

Java程式範例

[code lang="java"] //define discountService interface public interface DiscountSource { double discount(Item item); } // Tapestry AppModule.class public class AppModule { ... //item mapping to discount public static void contributeDiscountSource(MappedConfiguration config) { config.addInstance(Item.class, DefaultDiscountSource.class); config.addInstance(Book.class, VipDiscountSource.class); config.addInstance(Notebook.class, VipDiscountSource.class); } //build discountSource public static DiscountSource buildDiscountSource(Map configuration, StrategyBuilder strategyBuilder) { StrategyRegistry registry = StrategyRegistry.newInstance(DiscountSource.class, configuration); return strategyBuilder.build(registry); } ... } @Test public void testStrategyPattern() { DiscountSource discountSource = registry.getService(DiscountSource.class); Notebook nb = new Notebook(100); Item item = new Item(100); discountSource.discount(nb); discountSource.discount(item); } [/code]

利用StrategyBuilder產生DiscountSource,讓開發的人不需花時間處理strategy pattern細節,想法非常不錯。 當然不是每個人都使用Tapestry IoC但是可自行建構類似像StrategyBuilder工具來協助專案進行。

參考

http://tapestry.apache.org/strategybuilder-service.html

No comments:

Post a Comment