C# language and the singleton pattern

The authors consider the singleton pattern, the way it was presented in the GoF book, as some kind of anti-pattern. A lot has been written about how to implement it in a multi-core/multi-threaded environment. Constructs such as the double-checked locking pattern have been implemented to incorporate lazy loading while implementing singleton.

The C# programming language has got a nifty feature called a static constructor, which helps to implement the singleton pattern in a thread-safe manner. The static constructor is guaranteed to be called before any method (including the constructor) is called. We believe we can stop cutting down trees in order to write about the singleton pattern, at least in the .NET world.

    //--Chap1_06.cs 
    using System; 
 
    class SingleInstance 
    { 
      private int value = 10; 
      //----- In the case of Singleton Pattern, we make our 
      //----- ctor private to avoid instantiating the object using 
      //----- the new keyword 
      private SingleInstance() { } 
 
      //----- The static method acts as a mechanism to expose 
      //------ the internal instance 
      public static SingleInstance Instance {  
        get {  
          return Nested.instance; 
        }  
      } 
 
      private class Nested 
      { 
        static Nested() { } 
        internal static readonly SingleInstance instance 
        = new SingleInstance(); 
      } 
      public void Increment() 
      { 
        value++; 
      } 
      public int Value { get { return value; } } 
    } 
 
    public class SingletonExample 
    { 
      public static void Main(String[] args) 
    { 
      SingleInstance t1 = SingleInstance.Instance; 
      SingleInstance t2 = SingleInstance.Instance; 
      t1.Increment(); 
      if (t1.Value == t2.Value) 
        Console.WriteLine("SingleTon Object"); 
    } 
  } 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.84.29