class CMyClass
{
private:
CMyClass() {} // Private Constructor - prevent construction
CMySingleton(const CMySingleton&); // Prevent copy-construction
CMySingleton& operator=(const CMySingleton&); // Prevent assignment
static int nCount; // Current number of instances
static int nMaxInstance; // Maximum number of instances
public:
~CMyClass() // Public Destructor
{
--nCount; // Decrement number of instances
}
static CMyClass* CreateInstance() // Construct Indirectly
{
CMyClass* ptr = NULL;
if(nMaxInstance > nCount)
{
ptr = new CMyClass;
++nCount; // Increment no of instances
}
return ptr;
}
//Add whatever members you want
};
int CMyClass::nCount = 0;
int CMyClass::nMaxInstance = 1; // When maxInstance is 1, we have a pure singleton class
Practical usage of singleton is -
The OrderEvent class - the factory in the factory method design pattern.
All financial login screens etc are nice examples of singleton behaviour.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment