Singleton Pattern

Posted in Programming by tux4life on July 19, 2009

Using design patterns is a very effective way of making the code look neat, robust, reduce maintenance overhead.  Apart from these obvious advantages, design patterns also help convey certain special meaning and restrict programmers from doing things that they are not supposed to do.

For example consider a case where your application needs a Logger.  One can always write a Logger class but ideally you would want only one instance of the Logger class throughout your application.  This restriction can be forced by using the singleton pattern.  The following piece of code illustrates a singleton Logger class.

class Logger {

// The only way to get a reference for the logger class
// is to use the Instance() method
static Logger& Instance() {
static Logger theLog;
return theLog;

//     Expose the public methods of the Logger class here
//     void Write(char const *logline);
//     bool SaveTo(char const *filename);
// Hide the constructor

// Hide the copy constructor
Logger(Logger const&);

// Hide the assignment operator
Logger& operator=(Logger const&);

In the above implementation of the singleton pattern, the default constructor, copy constructor and the assignment operator are hidden.

You can also notice a static instance of the Logger class ‘theLog’ inside the Instance() function.  This function can be used to get a reference for the instance of the Logger class. The one and only instance of the Logger class is created when the Instance() method is called for the first time.  Creation of further instances are restricted as the constructor is hidden and the Instance() function returns a reference to a already created object.  And more over as there is no dynamic memory used, no explicit de-allocations are required.

To summarise, for creating the singleton object,

  1. Hide the default constructor
  2. Hide the copy constructor
  3. Hide the assignment operator
  4. Declare a public static method that returns a reference to a static instance of the class