2012-06-21 82 views
2

我有一個自定義對象ExportType創建同一類的不同實例,哪種設計模式?

public class ExportType{ 

    protected String name;  
    protected FetchingStrategy fetchStg; 
    protected ExportStrategy exportStg; 

    public ExportType(String name, FetchingStrategy fetch, ExportStrategy export) { 
      this.name = name; 
     this.fetchStg = fetch; 
     this.exportStg = export; 
    } 

    // ... 
} 

在我的應用程序必須創建具有不同FetchingStrategyExportStrategy出口類型的列表。通過實施新的FetchingStrategyExportStrategy,未來可以創建新的導出類型,所以我想設計我的應用程序以儘可能靈活。

有沒有一種設計模式可以用來獲得我所需要的? 爲每個ExportType創建不同的TypeFactory特定實例是否是正確的方法?

UPDATE

我試着總結一下我的問題:我正在將數據從一個數據庫導出一個Web應用程序。我有幾種方法從數據庫提取數據(ExportType s),這些類型是通過FetchingStrategyExportStrategy的不同組合獲得的。現在我需要創建一個這些「組合」列表來在必要時調用它們。我可以創建這樣的常量:

public static final ExportType TYPE_1 = new ExportType(..., ...); 

,但我想實現它的方式,所以我可以在未來的新組合/類型添加。

+1

有靈活性,然後是過度工程。要小心,你不會過分癡迷*使用什麼樣的模式*而不是*你需要解決什麼問題*。你又有什麼問題? – cHao

+0

@cHao你說得對 - 當你說的時候 - 注意你不會太過迷戀patterns_事實上我正在尋找一種方法來減輕我的工作。 :) – davioooh

回答

0

爲了儘可能靈活,不要使用具體的類。使用接口。

我會推薦Spring IoC在ExportType中注入FetchingStrategy和ExportStrategy的不同實現。

public class SomeExportType implements IExportType{ 

    protected String name; 
    @Autowired(@Qualifier="SomeFetchingStrategy")  
    protected IFetchingStrategy fetchStg; 
    @Autowired(@Qualifier="SomeExportStrategy")  
    protected IExportStrategy exportStg; 



    // ... 
} 

public interface IExportType { 
    public void doSomething(); // 
} 

public interface IFetchingStrategy { 
    public void fetch(); 
} 

public class SomeFetchingStrategy implements IFetchingStrategy { 

    public void fetch() { 
     //implement this strategy 
    } 

} 
1

對此的最佳設計模式是使用返回所有事物接口的工廠。您可以將所有實現抽象出來,從而可以靈活地擴展和更改系統。

春天依賴注入是該

你的最大的問題很可能是在數據庫級別,這是很難抽象

+0

我在你的答案附近:)是否這些工廠將返回匿名實現?我知道每次調用工廠時創建新對象效率不高。你能澄清一點嗎? – iozee

+0

@iozee最佳答案是在另一個答案中閱讀AbstractFactory的鏈接 – ControlAltDel

相關問題