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. private Singleton() { }
  5. public static Singleton Instance
  6. {
  7. get
  8. {
  9. if (instance == null)
  10. instance = new Singleton();
  11. return instance;
  12. }
  13. }
  14. //instance methods
  15. }

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. public class ExceptionLoggingService
  3. {
  4. private static ExceptionLoggingService _instance = null;
  5. public static ExceptionLoggingService Instance
  6. {
  7. get
  8. {
  9. if (Instance == null)
  10. {
  11. _instance = new ExceptionLoggingService();
  12. }
  13. return _instance;
  14. }
  15. }
  16. public void LogError(Exception ex)
  17. {
  18. try
  19. {
  20. }
  21. catch (Exception exx)
  22. {
  23. }
  24. }
  25. }