Creational Design Patterns

Singleton

Intent: Ensure a class only has one instance, and provide a global point of access to it.
Often only a single instance of a class is desirable in a program. The typical scenario is that of a manager of object of some sort (of windows, of accounts etc.)



The 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.

Use the Singleton pattern when there must be exactly one instance of a class, and it must be accessible to clients from a well-known access point. when the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.

Implementation:

class Singleton 
{ 
    public: 
        static Singleton* Instance(); 
    protected: 
        Singleton(); 
    private: 
        static Singleton* _instance; 
};

Singleton* Singleton::_instance = 0; 

Singleton* Singleton::Instance () 
{ 
     if (_instance == 0) 
       _instance = new Singleton;
    return _instance; 
}