我在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
類)的兩個實例得到了相同的屬性,那麼它實際上相同例如,這樣的「模式」更好的方式(同一標的參考)?
*任何*原因你實際上'新'''貨幣'?它看起來不像一個大班,因此沒有理由「新」。 – Xeo 2012-03-06 21:26:20
,因爲'Currency'類沒有公共構造函數,所以如果我創建一個包含'Currency'對象的映射,那麼在插入() – 2012-03-06 22:03:14
期間,如果我使用@ kennbrodhagen的解決方案適用於我),唯一剩下的問題是在程序結束時自動刪除貨幣對象。正如我所指出的那樣,我不能只持有貨幣對象,我必須新()他們......我不想創建一個具有所有接口等外部享元工廠。所以我會用'std :: map,boost :: shared_ptr >' –
2012-03-06 22:28:25