Singleton Class :- A class whose number of instances that can be instantiated is limited to one is called a singleton class. Thus, at any given time only one instance can exist, no more.
Where To Use Singlton Class :- The singleton design pattern is used whenever the design requires only one instance of a class. Some examples:
1) Application classes. There should only be one application class.
2) Logger classes. For logging purposes of an application there is usually one logger instance required.
Example:-
class CMyClass
{
private:
CMyClass() {} // Private Constructor
Static int nCount; // Current number of instances
Static int nMaxInstance; // Maximum number of instances
Public:
~CMyClass(); // Public Destructor
Static CMyClass *CreateInstance(); // Construct Indirectly
};
int CMyClass :: nCount = 0;
int CMyClass :: nMaxInstance = 1; // When maxInstance is 1, we have a pure singleton class
CMyClass:: ~CMyClass()
{
--nCount; // Decrement number of instances
}
CMyClass* CMyClass :: CreatInstance()
{
CMyClass* ptr = NULL;
if(nMaxInstance > nCount)
{
ptr = new CMyClass;
nCount++; // Increment no of instances
}
return ptr;
}
int main()
{
CMyClass* pObj = CMyClass::CreateInstance();
if(pObj)
{
// Success
}
else
{
// Failed to create, probably because the maximum number of instances has already
// been Created
}
delete pObj ;
return 0;
}
No comments:
Post a Comment