【发布时间】:2011-03-24 19:49:15
【问题描述】:
我想创建一个类,其中可能的实例范围有限,并且用户无法创建新实例。例如,货币是独一无二的,我正在工作的图书馆的用户不应该能够创建新货币或复制现有货币。我猜这有点像多吨模式。到目前为止我所拥有的是:
#include <string>
#include <boost/smart_ptr/shared_ptr.hpp>
struct Currency {
public:
typedef const Currency * Pointer;
std::string code;
static const Currency & Get(const std::string & Code);
private:
Currency();
Currency(const std::string & c);
};
Currency::Currency(const std::string & c)
:code(c) {}
const Currency & Currency::Get(const std::string & Code) {
typedef boost::shared_ptr<Currency> Value;
typedef std::map<std::string, Value> MapType;
static std::map<std::string, Value> map_;
if (map_.empty()) {
// Initialize your map here, from a database query or what have you...
}
MapType::const_iterator it = map_.find(Code);
if (it == map_.end()) {
throw std::exception(("[Currency::Get] Currency '" + Code + "' not found").c_str());
}
return *it->second;
}
这个设计有什么明显的问题吗? (我知道这不是线程安全的) 是否有一种我不知道的普遍接受的技术/模式传统上用于实现这一目标?
谢谢, 马克。
【问题讨论】:
-
听起来您正在寻找工厂模式,en.wikipedia.org/wiki/Factory_method_pattern。您的
Get()函数通常称为CreateInstance()函数,但您的想法是合理的。 -
地图会保存一份自己的字符串副本,所以公开:std::string 代码;应该用吸气剂代替。此外,工厂本身并不限制可用对象的数量。为什么要限制实例?
-
这不完全是工厂模式。我希望能够通过比较它们在内存中的地址来廉价地比较对象。即,我有两个现金流,它们是同一种货币吗? operator==(const Currnecy & rhs) 就变成了 {this == &rhs);}。在这种情况下,重要的是要确保不会无意中创建新的美元实例。
-
@Hazerider:你已经拥有了 90% 的工厂模式。你只需要调整它!
-
我想这真的是工厂和单身的混合体:-)
标签: c++ constructor unique instance private