Search This Blog

Thursday, November 10, 2011

Singleton Pattern implementation using Private Constructor in C#

In this article, I have tried to show the implementation of singleton pattern in C# using Private constructor. the source of this article is dofactory

using System;

namespace ConsoleApplication1
{
  /// <summary>
  /// MainApp startup class for Structural
  /// Singleton Design Pattern.
  /// </summary>
  class Program
  {
    /// <summary>
    /// Entry point into console application.
    /// </summary>
   public  static void Main()
    {
      // Constructor is private-- cannot use new
      Singleton s1 = Singleton.Instance(); // trick to creating object 
      Singleton s2 = Singleton.Instance();

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

      // Wait for user
      Console.ReadKey();
    }
  }

  /// <summary>
  /// The 'Singleton' class
  /// </summary>
  class Singleton
  {
    private static Singleton _instance;

    // Constructor is 'private'
    private Singleton()
    {
    }

    public static Singleton Instance()
    {
      // Uses lazy initialization.
      // Note: this is not thread safe.
      if (_instance == null)
      {
        _instance = new Singleton();
// creating the instance and guaranteeing for single instance 
      }

      return _instance;
    }
  }
}

Output
Objects are the same instance

1 comment :