Singleton design pattern

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
C# Design Patterns
edit
C# design pattern in a nutshell…
The Singleton design pattern is a way of ensuring that only a single instance of a class exists and of providing a single method of gaining access to it.


The Singleton design pattern is the most widely known pattern and the simplest of all patterns: The class diagram comprises a single class—the Singleton.

Use the Singleton design pattern when there must be only one instance of a class and it must be accessible to clients via a known access point.


C# design pattern at a glance…

Singleton is a class which permits itself to be instantiated only once. It…

  • has a private or protected constructor with no parameters.
  • has a single, global means of access via a static method.
  • cannot be subclassed nor instantiated with the new operator.
  • uses lazy instantiation.

Singleton can be used—in fact, is required—in many situations, for example:

  • caches
  • device drivers
  • dialog boxes
  • loggers
  • thread pools


Classic Singleton design pattern

The classic Singleton design pattern is often seen and quoted; however, it has a major flaw—it is not thread safe. Therefore, do not use it. It is shown here; so, it can be shown where its fault lies.

C# example of classic Singleton design pattern (lazy instantiation, thread unsafe)

// WARNING: This code is not thread safe!
 
using System;
 
public sealed class Singleton
{
 
   private static Singleton singleton;
 
   private Singleton() {} // private constructor
 
   public static Singleton GetInstance()
   {
      if (singleton == null)
      {
         singleton = new Singleton();  // lazy
         Console.WriteLine ("Singleton instantiated");
      }
      return singleton;
   }
}
 
class SingletonDemo
{
   static void Main()
   {
      Singleton objectA = Singleton.GetInstance();
      Singleton objectB = Singleton.GetInstance();
      // Singleton objectC = new Singleton();  - won't compile
      if (objectA == objectB)
      {
         Console.WriteLine ("Both refer to the same instance");
      }
   }
}


 Singleton design pattern (program output)
Singleton instantiated
Both refer to the same instance


Notes on classic Singleton design pattern

  1. It is not essential to mark members as private; since—unlike the Java language—, the default access is private.
  2. It is not essential to make the class sealed; since, Singleton cannot be subclassed already due to its private constructor.
  3. One could just as easily use a static property named Instance in lieu of the GetInstance() method.
public static Singleton Instance
{
   get
   {	        
      if (singleton == null)
      {
         singleton = new Singleton();
      }
      return singleton;
   }
}


Previous_Page_.gif Next_Page_.gif

Personal tools