Possible Duplicates:
Singletons: good design or a crutch?
Problems with Singleton Pattern
Singleton: How should it be used
Hi.. Please help me up to understand what is the use of singleton class
Thank you
Possible Duplicates:
Singletons: good design or a crutch?
Problems with Singleton Pattern
Singleton: How should it be used
Hi.. Please help me up to understand what is the use of singleton class
Thank you
The purpose of the singleton pattern is to ensure that only one instance of a class ever exists. This is achieved by making the constructor for the class private and forcing clients to access the instance via a static member function, often just called instance
, which is responsible for creating and managing the single instance.
In the general case, singletons are really an anti-pattern and should not be used.
A singleton class is designed to control the creation of instances of that class so that only one such instance can be created.
e.g.
class Singleton {
public:
static void createInstance() { instance = new Singleton(); }
static Singleton& getInstance() { return *instance; }
int getValue() { return value; }
private:
Singleton() { value = 4; }
int value;
static Singleton *instance;
};
...
Singleton.createInstance();
int x = Singleton.getInstance().getValue();
One example of Singleton class is Think you have a memory map and a calss to create and write info to the memory map. To avoid the inheriting or containing classes to create multiple instances we can go for this singleton approach.
Singleton is a design pattern used to control the number of instantiations of a class, usually only one.
class Singleton
{
private:
Singleton() {} // the constructor is private, so non reachable from outside the class
public:
static Singleton& getInstance()
{
static Singleton instance;
return instance;
}
}
The example code lets you create only one instance of Singleton. Like James already wrote, Singletons often produce more problems than they solve. Another good article about singltons can be found here