Tuesday, June 10, 2008

Singleton pattern realisation

This is the correct implementation of the Singleton design pattern. It is easier to not have the lazy-initialization option, but if you have to then go on with the following example.
And here is it's implementation on C#.

public class SingletonTest
{
  private static SingletonTest instance;
  private static readonly Object syncRoot = new Object();
 
  private SingletonTest ()
  {
  }

  public static SingletonTest Instance
  {
    get
    {
      if (instnace == null)
      {
        lock (syncRoot)
        {
          if (instance == null)
          {
            instance = new SingletonTest();
          }
        }
      }
     
      return instance;
    }
  }
}