Introduction
Ensures a class has only one object and provides a global access point.This falls under the category of Creational Design pattern.There is lot of explanation around the internet which makes me confused and I feel difficult to understand it initially. I am writing this article to provide straight forward explanation which may helpful to developers who are in the same category.Static Class vs Singleton Design Pattern
Static class is initialized when loaded first and it will be stored in stack.In simple words, static class is eagerly loaded which may cause performance issues.Since it is stored in stack , we can't dispose it or garbage collector doesn't have anything to deal with it.Simply only static methods or static constructors are allowed within it and constructor will be invoked only once when class is loaded.This can't be inherited or cloned and so extension of this class will be nightmare.Think about the situation from where you want single object to be stored in heap and it should be instantiated whenever on demand, there comes singleton pattern.
Different ways of Implementation
There are different ways of implementation
- No thread safe
- Thread safe
- Double check thread safe
- Eager Instantiation
- Lazy Instantiation
Real World Examples
We can understand the singleton pattern better with some real world examples.when you surfed in internet you can get lot of abstract examples which will not give exact point where we can use it in our system and even I too felt the same when I started learning about singleton.There are some examples like
- DB Connection
- Error Log
- Hardware Check
But as of now lot of frameworks are available to handle such situation by theme self and so I would like to explain singleton pattern from my own experience in straight forward way and so every one who are reading my article can understand in easier way.
Problem Statement
Design a Token system that should generate unique tokens for all users who logged in to the system.write a c# program to achieve this.
Since I want to provide the straight forward solution to understand the Singleton Design pattern better , I have choose the Lazy Instantiation way of implementation while other type of implementation is expensive than .NET 4 Lazy Instantiation.Solution
TokenSystem Class
/// <summary>
/// Sealed Key word will not allows you to Inherit and so this Token system class will act as a base class
/// </summary>
public sealed class TokenSystem
{
/// <summary>
/// Private constructor will not allows you to Instantiate object
/// </summary>
private TokenSystem() { }
private static readonly Lazy<TokenSystem> lazy = new Lazy<TokenSystem>(()=>new TokenSystem());
public static TokenSystem Instance
{
get
{
return lazy.Value;
}
}
/// <summary>
/// Should ensure the thread safety by providing lock
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public string GenerateToken(string userId)
{
return "New Unique Token to Logged in User - " + userId;
}
}
Client
namespace SingletonPattern
{
class Program
{
static void Main(string[] args)
{
string _loggedinuserId1 = "1";
string _loggedinuserId2 = "2";
string _token1 = "";
string _token2 = "";
_token1=TokenSystem.Instance.GenerateToken(_loggedinuserId1);
_token2 = TokenSystem.Instance.GenerateToken(_loggedinuserId2);
}
}
}
Comments
Post a Comment