Singleton class
-
What is a singleton class? Plz explain me with a suitable example. Thanks in advance Rajendra
-
What is a singleton class? Plz explain me with a suitable example. Thanks in advance Rajendra
Do you hate google? :doh: You could have searched with "Singleton C++" and would get lots of resources where you could have read from A class whose number of instances is only one is called a singleton class. only one instance of a class can exist at any given time. A raw class definition would be similar to what is mentioned below
class CXSingleton { public: static CXSingleton& Instance() { static CXSingleton ston; return ston; } };
And yes there are n number of ways of implementing this
You need to google first, if you have "It's urgent please" mentioned in your question. ;-)_AnShUmAn_
-
What is a singleton class? Plz explain me with a suitable example. Thanks in advance Rajendra
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/