Jul 052012
 

Singleton patterns are used, when you want to allow creation of only one instance(object) of a particular class. Such classes (which allow only single object to be created) are called Singleton Classes. For example, there is only one Window manager, so a class implementing Windows Manager, should be allowed to be instantiated only once.

One way to allow only one object creation is to have everything in the class (data and methods) static and global. Because static members are available at class level and have only a single copy. But this is not an Object Oriented Design Methodology plus this will not disallow creation of objects, we can create as many projects of a class, and the responsibility to disallow multiple objects should lie with the class and not with the user. User should be free to use the class, if an attempt is made to create multiple objects of the class, then it should result in a compile-time error.

Singleton Pattern is part of the Creational Design Pattern because it effects the way in which an object of a class is getting created.

Implementation of Singleton Design Pattern:

    class Singleton 
    {
      public:

        static aSingletonClass *getInstance()
        {
            //The object is created when it is called first
            if(!_instance)
               _instance = new Singleton;
            return _instance;
        }

        static void deleteInstance()
        {
            if(_instance)
            {
               delete _instance;
              _instance = NULL; //To avoid memory leak
            }        
        }

      private:
          static Singleton *instance_;

          Singleton();  // Private Constructor
          ~Singleton() {}; // Private Destructor, noone can delete the object explicitly 

         // Preventing creation of object by Copy or by assignment.
          Singleton(const Singleton&);
          Singleton& operator=(const Singleton&); 
    };

Note that the Constructor (default & Copy constructor) and overloaded assignment operator are only declared and not defined, but the destructor is defined. This is explained below:

If we define the constructor then object of the class can be created in a friend class or friend function. Though we have not yet declared any function or class as friend, but if we do , our code should not stopped functioning.

The destructor is defined, because we need to destroy the object (the only object) which is getting created.

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)