单件模式
单件模式也是比较常用的设计模式之一,指的是在一个进程当中一个类只有一个实例。单件模式比较简单,这里就不详细说了。
下面的代码来源于QL:
//! Basic support for the singleton pattern.
/*! The typical use of this class is:
/code
class Foo : public Singleton<Foo> {
friend class Singleton<Foo>;
private:
Foo() {}
public:
...
};
/endcode
which, albeit sub-optimal, frees one from the concerns of
creating and managing the unique instance and can serve later
as a single implemementation point should synchronization
features be added.
/ingroup patterns
*/
template <class T>
class Singleton : private boost::noncopyable {
public:
//! access to the unique instance
static T& instance();
protected:
Singleton() {}
};
#if defined(QL_ENABLE_SESSIONS)
// definition must be provided by the user
Integer sessionId();
#endif
// template definitions
template <class T>
T& Singleton<T>::instance() {
static std::map<Integer, boost::shared_ptr<T> > instances_;
#if defined(QL_ENABLE_SESSIONS)
Integer id = sessionId();
#else
Integer id = 0;
#endif
boost::shared_ptr<T>& instance = instances_[id];
if (!instance)
instance = boost::shared_ptr<T>(new T);
return *instance;
}