Friday, February 11, 2011

Singleton

Singleton pattern

This pattern is a commonly used design pattern on most of the object oriented programming.
The basic idea is only one instance of a class ever exists if it is designed as singleton..
To make a class singleton the following criteria must be there.

  1. Define a private static attribute in the “single instance” class.
  2. Define a public static accessor function in the class.
  3. Do “lazy initialization” (creation on first use) in the accessor function.
  4. Define all constructors to be protected or private.
  5. Clients may only use the accessor function to manipulate the Singleton.
C# Code

class Singleton
  {

    private static Singleton instance;

    // Note: Constructor is 'protected' or private
    protected Singleton()
    {
    }

    public static Singleton GetInstance()
    {
      // Use 'Lazy initialization'
      if (instance == null)
      {
        instance = new Singleton();
      }

      return instance;
    }
  }

static void Main()
    {
      // Constructor is protected -- cannot use new
      Singleton s1 = Singleton.GetInstance();
      Singleton s2 = Singleton.GetInstance();

      if (s1 == s2)
      {
        Console.WriteLine("Objects are the same instance");
      }

    }

No comments:

Post a Comment