Skip to main content

Singleton Design Pattern

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 
  1. No thread safe 
  2. Thread safe
  3. Double check thread safe
  4. Eager Instantiation
  5. 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
  1. DB Connection
  2. Error Log
  3. 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.

Solution

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.
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);
        }
    }
}

Conclusion

I hope this article help you to understand the singleton pattern and its usage in real world .Since I am trying to share my knowledge to all of you and If any feedback about this article is almost welcome.So that it will be helpful for me to shape the article in best way.

Comments

Popular posts from this blog

How to resolve ASP.NET core web API 2 mins timeout issue

Introduction We are in the new world of microservices and cross-platform applications which will be supported for multiple platforms and multiple heterogeneous teams can work on the same application. I like ASP.NET Core by the way its groomed to support modern architecture and adhere to the software principles. I am a big fan of dot net and now I become the craziest fan after seeing the sophisticated facility by dot net core to support infrastructure level where we can easily perform vertical and horizontal scaling. It very important design aspect is to keep things simple and short and by the way, RESTFul applications are build and it is a powerful mantra for REST-based application and frameworks. Some times we need to overrule some principles and order to handle some situations. I would like to share my situation of handling HTTP long polling to resolve the ASP.Net core 2 mins issue. What is HTTP Long polling? In the RESTFul term, when a client asks for a query from the serv

How to Resolve ASP.NET Core Key Protection Ring Problem in AWS Lambda

Introduction When it comes to server less web application design using asp.net core razor pages, we definitely need to consider a factor of data protection key management and its lifetime in asp.net core. I developed a site using AWS toolkit of ASP.NET Core Razor Pages. The main advantage of ASP.NET Core is cross-platform from where we can deploy our application in MAC, Linux or windows. I deployed my site initially in IIS Server from which I got the results as expected .but later period I decided to host my site in AWS Lambda in order to meet our client requirement. Strangely, I got unexpected behavior from my site. I just refer the cloud information Lambda Log to identify or pinpoint the case, I got the error Information like “Error Unprotecting the session cookie” from the log. In this article, I tried to explain the root cause of the problem and its solution to overcome such kind of issue. Data Protection in ASP.NET Core This is feature in ASP.NET Core which acts as repl

Which linq method performs better: Where(expression).FirstorDefault() vs .FirstOrDefault(expression)

 Introduction When it comes to LINQ, we always have multiple options to execute the query for the same scenario. Choosing correct one is always challenging aspect and debatable one. In one of our previous articles   Any Vs Count  , we have done performance testing about best LINQ methods over .NET types. In this article, I would like to share about  Where(expression).FirstorDefault() vs .FirstOrDefault(expression) Approaches Performance testing for  Where(expression).FirstorDefault() vs .FirstOrDefault(expression) is very interesting IEnumerable<T> or ICollcetion<T>  .FirstOrDefault(expression) is better than  Where(expression).FirstorDefault() Public API To check the performance, I need some amount of data which should already available. So I decided to choose this  public api . Thanks to publicapis Public API Models Entry class using System ; using System.Collections.Generic ; using System.Text ;   namespace AnyVsCount { public class Entry { pub