2012-03-06 104 views
0

我在C++項目中遇到了「設計」問題。在工廠內管理類實例的更好方法是什麼?

我有一個類,命名爲Currency(可"USD""EUR",等等...,並得到了一些方法) 有項目該類新-ED隨處可見的許多情況,但可以有隻有一堆不同的貨幣(〜100)。

所以我寫了分配Currency第一次它的問法,否則返回現有Currency

class Currency 
    { 
    public: 
     typedef std::map<std::string, Currency*> CurrencyMap_t; 
    public: 
     static CurrencyMap_t _currencies; 

    public: 
     static const Currency& getCcy(const std::string& name) 
     { 
     CurrencyMap_t::const_iterator it(_currencies.find(name)); 

     if (it == _currencies.end()) 
      it = _currencies.insert(std::make_pair(name, new Currency(name))).first; 

     return *(it->second); 
     } 

    private: 
     // can't instantiate from outside 
     Currency(); 
     Currency(const Currency& other); 
    private: 
     // private ctor 
     explicit Currency(const std::string& name) {... } 
    }; 

所以,現在,我只有每個不同Currency的一個實例。

但是,我不能再有一個類持有Currency成員,因爲默認的構造函數沒有定義:

class CcyPair 
    { 
    public: 
     CcyPair(const Currency& ccy1, const Currency& ccy2) {} 
    private: 
     Currency _ccy1; // won't compile because "no default-constructor available" 
     Currency _ccy2; 
    }; 

而且我不想CcyPair類來保存Currency指針。

你一定要實現這保證瞭如果一個類(這裏的Currency類)的兩個實例得到了相同的屬性,那麼它實際上相同例如,這樣的「模式」更好的方式(同一標的參考)?

+1

*任何*原因你實際上'新'''貨幣'?它看起來不像一個大班,因此沒有理由「新」。 – Xeo 2012-03-06 21:26:20

+0

,因爲'Currency'類沒有公共構造函數,所以如果我創建一個包含'Currency'對象的映射,那麼在插入() – 2012-03-06 22:03:14

+0

期間,如果我使用@ kennbrodhagen的解決方案適用於我),唯一剩下的問題是在程序結束時自動刪除貨幣對象。正如我所指出的那樣,我不能只持有貨幣對象,我必須新()他們......我不想創建一個具有所有接口等外部享元工廠。所以我會用'std :: map ,boost :: shared_ptr >' – 2012-03-06 22:28:25

回答

1

我知道你說過你不想持有指向貨幣對象的指針,但是你會如何看待持有參考?我不確定是否想要避免使用指針,這樣您就不會因爲對NULL的大量檢查而感到沉重負擔,或者如果您有其他原因。這裏是一個使用參考CcyPair的例子:

class CcyPair 
     { 
     public: 
     CcyPair(const Currency& ccy1, const Currency& ccy2) 
      : _ccy1(ccy1), _ccy2(ccy2) {} 

     CcyPair(const std::string& ccyName1, const std::string& ccyName2) 
      : _ccy1(Currency::getCcy(ccyName1)), _ccy2(Currency::getCcy(ccyName2)) {} 

     private: 
     // need to make these const since getCcy returns const 
     // you could also change the signature of getCcy to return non-const 
     const Currency & _ccy1; 
     const Currency & _ccy2; 
     }; 
+0

是的,你是對的。它似乎是更好的「替代」 – 2012-03-06 22:11:31

+0

(在靜態std :: map中使用boost :: shared_ptr <>自動刪除對象) – 2012-03-06 22:29:26

3

你在找什麼是享元模式。閱讀http://en.wikipedia.org/wiki/Flyweight_pattern

順便說一句,輕量級,你也可以有一個相關的狀態,但必須將該狀態過濾到一個單獨的類。

+0

是的,事實上,Flyweight模式更多或者像我在示例中實現的那樣。 – 2012-03-06 22:16:01

相關問題