Singleton
Before moving to the Singleton Design Pattern, let's first understand what a singleton is.
Singleton allows creating only one object to a class and this class restricted to one instance provides a global point of access to it.
Advantages
The advantages of a Singleton Pattern are,
- It supports lazy loading.
- Support of Static Initialization.
- It has a single point of access to a particular instance and it is very easy to maintain.
Disadvantages
Singleton class vs. Static methods
The following points compare the Singleton class vs. Static methods,
- A Static Class cannot be extendable whereas a singleton class can be extended.
- A Static Class is able to instantiate but a singleton class prevents it.
- Singleton supports STATE initialization whereas Static Class not.
- When program or namespace containing the class is loaded, the static class is loaded automatically by the CLR.
Implementation of the singleton design pattern class
The following code is for a thread-safe implementation of the singleton pattern.
Implementation of the Singleton Design Pattern
First version - not thread-safe,
- // Bad code! Do not use!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace ConsoleApplication {
- publicsealedclass SingletonClass {
- //Self instance of the class
- privatestatic SingletonClass _instanceSingleton = null;
- //Private constructor to restrict class inhertiance
- private SingletonClass() {}
- publicstatic SingletonClassInstance {
- get {
- if (_instanceSingleton == null) {
- _instanceSingleton = new SingletonClass();
- }
- return _instanceSingleton;
- }
- }
- }
- }
This is not thread-safe. Becuase it voilates the singleton pattern when two different threads could both have evaluated the test if (_instanceSingleton==null) and found it to be true, then both create instances.Factually the instance may be created already before the expression is evaluated, but the memory model doesn't guarantee that the new value of instance other threads can see unless suitable memory pass.
Thread-safety using double-check locking

Join the conversation! Your thoughts help the community grow.