Singleton Pattern

Introduction and Implementation of Singleton Pattern

Category: Design Patterns Tags: C#


        Singleton Design Pattern is creational design pattern which is used when we want to restrict a class’s object creation to one. Singleton keeps only one object of a class which is useful in some scenarios like we have to create a list of online users across application.


        To implement Singleton we will create a list of user’s which will contain their name and authentication status across the application. For that we will use user defined datatype to store name and authentication status:

class Identity
    public string Name { get; set; }
    public bool IsAuthenticated { get; set; }

Now we will create singleton class:

class User
    //Object of class inside same class
    private static User _user;
    //username-identity pair     private Dictionary<string, Identity> _users = new Dictionary<string, Identity>();
    ///<summary>     /// Private constructor prevents object creation     ///</summary>     private User()     { }
    //Useful for safe multi-threading     private static object syncLock = new object();
    public static User Instance     {         get         {             if (_user == null)             {                 lock(syncLock)                 {                     _user = newUser();                     return _user;                 }             }             else                 return _user;         }     }
    ///<summary>     /// Indexer     ///</summary>     ///<param name="user">user name</param>     ///<returns></returns>     public Identity this[string user]     {         get{ return _users[user]; }         set{ _users[user] = value; }     } }

Above class is a Singleton class which has its own object created inside as well having private constructor which prevents any other object creation. So we have _user field which will be returned by property Instance, we are locking syncLock which is object class's reference simply makes it multi-thread safe. At last we are having an indexer which can return an existing user from dictionary or can add users. Below you can see how to execute this code:

//adding usernames with name and authentication status
User.Instance["nikhil_123"] = new Identity() { Name = "Nikhil", IsAuthenticated = false };
User.Instance["manju@1"] = new Identity() { Name = "Manju", IsAuthenticated = true };
//retrieving data using username
Console.WriteLine("Is {0} authenticated?: {1}", User.Instance["nikhil_123"].Name, User.Instance["nikhil_123"].IsAuthenticated);
Console.WriteLine("Is {0} authenticated?: {1}", User.Instance["manju@1"].Name, User.Instance["manju@1"].IsAuthenticated);

And output of above code will be:


Is Nikhil authenticated?: False

Is Manju authenticated?: True


So we can see we have only one object of User class which is "Instance" and we can not create any other object.

Like 0 People
Last modified on 16 June 2018
Nikhil Joshi

Nikhil Joshi
Ceo & Founder at Dotnetlovers
Atricles: 139
Questions: 12
Given Best Solutions: 12 *


No Comments Yet

You are not loggedin, please login or signup to add comments:

Existing User

Login via:

New User