What is a Singleton class?
- This is a creational design pattern.
- A design pattern to provide one and only instance of an object.
- Make the constructors of the class private.
- Store the object created privately.
- Provide access to get the instance through a public method.
- Can be extended to create a pool of objects.
EXAMPLE: Demonstrates the implementation of a singleton class
#include <iostream>
using namespace std;
// Singleton class
class MySingleton {
public:
static MySingleton* iInstance;
public:
static MySingleton* GetInstance();
private:
// private constructor
MySingleton();
};
MySingleton* MySingleton::iInstance = NULL;
MySingleton::MySingleton()
{
cout << "In construtor ..." << endl;
}
MySingleton* MySingleton::GetInstance()
{
if ( iInstance == NULL ) {
iInstance = new MySingleton();
}
return iInstance;
}
void main()
{
MySingleton* obj;
obj = MySingleton::GetInstance();
}
OUTPUT:
In construtor ... (displayed only once)






0 comments:
Post a Comment