Technical Interview Questions

The largest pool of technical questions with answers, explantions, code and detailed analysis

Archive for October 19th, 2006

Singleton Pattern: Part 1 Trivial implemenation

Posted by tekpool on October 19, 2006

Singleton Pattern: Part 1 Trivial implemenation

The purpose of a singleton pattern is to ensure a unique instance of the class and to provide global access to this. It falls under the Creational patterns category.

The class implementing the singleton pattern will have to do the following items:

  1. Provide an Instance Creation Method to the user.
  2. Maintain the unique instance throughout the life of the program(s) in which this class is created.

To maintain the unique instance, the class will have to remove the normal object creation procedure away from the user. The normal object creation is through the constructor. Taking this away from the user would mean, making the constructor as private or protected. With the absence of a public constructor, the class now can take total control on how its instances are created. The only way to do this, is to provide a static method (say CreateInstance). Why static? Because, the user can actually call this method without creating an object (which is obviously out of the user’s control).

The logic of the CreateInstance method is pretty straightforward. Check, if any instance has already been created, if yes, return the instance, else create and store the instance and return it. It is obvious here again, storing the instance has to be done in a private static variable, static because, you are doing this in a static method, private because, you need to do the maintenance of the singleton instance creation.

Here’s the code sample to demonstrate this. I am going to promote Test Driven Development in my examples.

The TestApp::TestSingleton() method is the test code that I wrote even before writing the actual Singleton class. I will discuss Test Driven Development in detail in another series.

  class TestApp 
  { 
    public: 
    static void TestSingleton() 
    { 

      Singleton s1 = Singleton.Instance(); 
      Singleton s2 = Singleton.Instance(); 

      if (s1 == s2) 
      { 
        printf("PASSED:  
        Objects are of the same instance"); 
      } 
      else 
      { 
        printf("FAILED:  
       Objects do not point to the same instance"); 
      } 

    } 
  } 

// WARNING: DO NOT USE THIS CODE ANYWHERE. 
// THIS IS A VERY TRIVIAL IMPLEMENATION. WE WILL 
// DISCUSS THE ISSUES WITH THIS IN FUTURE POSTS. 

  class Singleton 
  { 
    private: 
    static Singleton instance; 

    protected Singleton() 
    { 
    } 

    public static Singleton CreateInstance() 
    { 

      if (instance == null) 
      { 
        instance = new Singleton(); 
      } 

      return instance; 
    } 
  } 
}

Advertisements

Posted in C++, Design Patterns, General, Microsoft, Progamming Languages | 1 Comment »