Singleton! Intent Ensure a class only has one instance, and provide a global point of access to it. Motivation It's important for some classes to have exactly one instance. Although there can be many printers in a system, there should be only one printer spooler. There should be only one file system and one window manager. A digital filter will have one A/D converter. An accounting system will be dedicated to serving one company. How do we ensure that a class has only one instance and that the instance is easily accessible? A global variable makes an object accessible, but it doesn't keep you from instantiating multiple objects. A better solution is to make the class itself responsible for keeping track of its sole instance. The class can ensure that no other instance can be created (by intercepting requests to create new objects), and it can provide a way to access the instance. This is the Singleton pattern.
class CSingleton
{
public:
static CSingleton * getInstance() {
if (!_singleton) _singleton = new CSingleton;
return _singleton;
}
protected:
CSingleton() { }
~CSingleton() { }
private:
static CSingleton * _singleton;
};
CSingleton* CSingleton ::_singleton = NULL;
Try to look at singleton destroyers too especially when you singleton holds a database connection or similar resources. You can also create a SINGLETON TEMPLATE like the one below. In this way your singleton holds a pointer and it ensures that only one instance exists of the object the pointer is pointing at.
template < typename T >
class CSingleton
{
public:
static CSingleton * getInstance() {
if (!_singleton) _singleton = new CSingleton;
return _singleton;
}
// Access to the pointer, but NOT the singleton itself
const T* operator->() { return m_ptr; };
protected:
CSingleton() { m_ptr = new T; }
~CSingleton() { if (m_ptr) delete m_ptr; }
private:
static CSingleton * _singleton;
T * m_ptr;
};
Hth
-- Jess Nielsen, b.sc. Security Analyst http://jessn.blogspot.com/