Singleton Design Pattern

From JholJhapata
Revision as of 17:49, 9 December 2019 by Admin (talk | contribs)

The singleton pattern is a software design pattern that restricts the instantiation of a class to one single instance. This is useful when exactly one object is needed to coordinate actions across the system.

Singleton

Problem

Application needs one, and only one, instance of an object.

Example

Let’s take a look at an example, which is creating multiple objects.

   class Program
   {
       static void Main(string[] args)
       {
           SingleTon obj1 = new SingleTon();
           SingleTon obj2 = new SingleTon();
           Console.WriteLine("Main End");
           Console.ReadLine();
       }
   }
   class SingleTon
   {
       private static int objectCounter = 0;
       public SingleTon()
       {
           objectCounter++;
           Console.WriteLine("objectCounter : " + objectCounter.ToString());
       }
       public void printText(string strData)
       {
           Console.WriteLine(strData);
       }
   }

Output

   objectCounter : 1
   objectCounter : 2
   Main End

Solution

The common characteristics of a Singleton Pattern:

  • A single constructor, that is private and parameter-less.
  • The class is sealed.
  • A static variable that holds a reference to the single created instance, if any.
  • A public static means of getting the reference to the single created instance, creating one if necessary.

First version - not thread-safe

Output

Second version - simple thread-safety

Output

Third version - attempted thread-safety using double-check locking

Output

Singleton class vs. Static class