在一个C++项目中,我遇到了一个“设计”问题。
我有一个类,名为Currency (可以是"USD"、"EUR"等等,并得到一些方法)--这个类的许多实例在项目中到处都是新的,但是只能有一堆不同的货币(~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;
};我不想在Currency类中保存CcyPair指针。
您是否有更好的方法来实现这样一个“模式”,以确保如果一个类的两个实例(这里是Currency类)具有相同的属性,那么它实际上是相同的实例(相同的底层引用)?
发布于 2012-03-06 21:17:49
我知道你说过你不想保存指向货币对象的指针,但是你对持有引用有什么感觉呢?我不确定您是否希望避免指针,这样您就不会承受大量空检查的负担,或者您是否有其他原因。下面是一个使用引用的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;
};发布于 2012-03-06 21:02:51
你要找的是飞度模式。读取http://en.wikipedia.org/wiki/Flyweight_pattern
顺便说一句,在飞重方面,您也可以有一个关联的状态,但是必须将该状态过滤到一个单独的类中。
https://stackoverflow.com/questions/9591799
复制相似问题