Overview Of Singleton Pattern

What is a Singleton Pattern?

Singleton Pattern is one of the software design patterns which uses only one instantiation of a class.

When do we use a Singleton Pattern?

When you want a single instance of a class to be active throughout the application lifetime.

Example - Error Logger

When values on one screen need to be utilized on another screen without the usage of Session concept. Example - Logged User Details

Difference between Static Class and Singleton Pattern

Static ClassSingleton Pattern
Cannot be instantiated.Only one instance throughout the cycle.
Can contain only static members & static methods.Can contain both static and non-static variables and methods.
Cannot have a simple public constructor.Can have a simple public constructor.

Implementation

Add a static implementation of the same class datatype as one of the fields/properties.

  1. public class Singleton  
  2.     {  
  3.         private static Singleton instance;  
  4.    
  5.         private Singleton() { }  
  6.    
  7.         public static Singleton Instance  
  8.         {  
  9.             get  
  10.             {  
  11.                 if (instance == null)  
  12.                     instance = new Singleton();  
  13.                 return instance;  
  14.             }  
  15.         }  
  16.    
  17.         //instance methods  
  18.     }  

Exception Logger

When you want to log the exception, you don’t need to instantiate every time you want to log. A single object can be used to log the exceptions. Below is a sample implementation of Exception Logging Service.

Code Snippet

  1. using System;  
  2.   
  3. public class ExceptionLoggingService  
  4. {  
  5.     private static ExceptionLoggingService _instance = null;  
  6.   
  7.     public static ExceptionLoggingService Instance  
  8.     {  
  9.         get  
  10.         {  
  11.             if (Instance == null)  
  12.             {  
  13.                 _instance = new ExceptionLoggingService();  
  14.             }  
  15.             return _instance;  
  16.         }  
  17.     }  
  18.   
  19.     public void LogError(Exception ex)  
  20.     {  
  21.         try  
  22.         {  
  23.   
  24.         }  
  25.         catch (Exception exx)  
  26.         {  
  27.   
  28.         }  
  29.     }  
  30. }