[X]

C# Singleton Design Pattern - Design Patterns in Action

Singleton Design Pattern

This pattern is used where only one instance of the object is required and shared among all the clients. The same instance is maintained throughout the entire life cycle of the class object. This is not handled by the client code rather it is the responsibility of the class to make sure that only one intsance exists throughout all the client calls.


So how this is possible? If I have access to the class I can create as many instances by just using new.

That is not true. If I make the constructor private, I can not create object using new.

But then how I will get the object? This is further done by exposing a public static GetInstance (you can give it any meaningful name) method/property.

  • A private static variable of the Singleton Class type is defined and intantiated in the private static constructor of the class. So when a call occurs to the GetInstance method this same static object is returned.
  • Also as best practice it is ensured that private static instance variable is instantiated only when it is required.
  • Also there exist thread safe version of this Singleton Class by putting a lock while instantiating the class object. We also mark singleton class as sealed to make it more safe, so that no subclass can attempt to intantiate and get more that one instance.

 

Singleton Advantages:

  • It makes sure that only one instance of the class exists
  • Can get access to data in this class from anywhere

Singleton Disadvantages:

  • Acts like global variable
  • Can cause methods to have unintended and unintefied side effects due to data sharing via state in the singleton


Steps to implement Singleton Pattern:

  1. Make constructor private
  2. Add a private static object which will be internally instantiate using the private static constructor
  3. Add a public static property which will return the instance of the class

 

So lets begin and code the singleton design pattern.

1. Create a SingletonPattern class library project

2. Create a Singleton.cs class and write below code

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SingletonPattern
{
    public sealed class Singleton
    {
        //create a variable to maintain the timestamp when object was created
        private DateTime _objectCreatedOn;
        //create object of the class which will intantiate at once
        private static Singleton _instance = null;

        //create a static readonly sync object to make it thread safe
        private static readonly object _syncLock=new object();

        //make default constructon private
        Singleton() {
            _objectCreatedOn = DateTime.Now;
        }

        //create a public static property which will return the only instance of the class
        public static Singleton Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_syncLock)
                    {
                        //double check (not necessarily required), just to make it more safe
                        if (_instance == null)
                        {
                            _instance = new Singleton();
                        }
                    }
                }
                return _instance;
            }
        }

        //get the time when object was created
        public DateTime ObjectCreatedOn
        {
            get { return _objectCreatedOn; }
        }

    }
}

 

 

 

3. Create a SingletonClient console project.

4. Add below code to the Program.cs file

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SingletonPattern;
namespace SingletonClient
{
    class Program
    {
        static void Main(string[] args)
        {
            //craete first object of Singleton Class and check it's creationgtime
            Singleton firstSingleton = Singleton.Instance;
            Console.WriteLine("firstSingleton object was created on {0}", firstSingleton.ObjectCreatedOn.ToString());
            Console.ReadLine();
            //create second object of Singleton Class and check it's creation time
            Singleton secondSingleton = Singleton.Instance;
            Console.WriteLine("secondSingleton object was created on {0}", secondSingleton.ObjectCreatedOn.ToString());
            Console.ReadLine();
        }
    }
}

 

 

 

5. Run the this project and see the output.

 

We learn about the basics of singleton pattern. How to define a Singleton class? How to make Singleton class thread safe in C#?

Some points to note: There are several other patterns which make implicit assumption that only one instance of the class will created. Facade pattern is one of them. There should be only one instance of a facade class. And this can be done by implementing Singleton pattern.

blog comments powered by Disqus

Posts By Month