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 Class | Singleton 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.
- public class Singleton
- {
- private static Singleton instance;
-
- private Singleton() { }
-
- public static Singleton Instance
- {
- get
- {
- if (instance == null)
- instance = new Singleton();
- return instance;
- }
- }
-
-
- }
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
- using System;
-
- public class ExceptionLoggingService
- {
- private static ExceptionLoggingService _instance = null;
-
- public static ExceptionLoggingService Instance
- {
- get
- {
- if (Instance == null)
- {
- _instance = new ExceptionLoggingService();
- }
- return _instance;
- }
- }
-
- public void LogError(Exception ex)
- {
- try
- {
-
- }
- catch (Exception exx)
- {
-
- }
- }
- }