Singleton Pattern: Generics Way

Singleton Pattern:  it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance.

Below implementation is a step forward with aim to make it generic so as to decouple it from a particular class type.

  • Hemant

    Hi Sachin,

    few questions:

    Will this code work in MultiThreaded Environment?
    what is the benefit of having internal class inside public class?

    • For Multithreaded environment, we have to use lock() and thus implementation gets a little mofified as below:

      using System;

      public sealed class Singleton
      {
      private static volatile Singleton instance;
      private static object syncRoot = new Object();

      private Singleton() {}

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

      return instance;
      }
      }
      }

      Also see: http://csharpindepth.com/Articles/General/Singleton.aspx