Singleton Design Pattern

The singleton pattern ensures that, “A class has only one instance and provides a global point of access to it“. It comes under the creational design pattern.

Just think about that, you have a class and singleton pattern helps you to make it impossible to instantiate that class except for a single time and whenever you ask a class for second instance, it returns the same first instance.

There are two things, you want to understand, one is about making sure that you only have a single instance and other one is providing global access to that instance.

Dangers of SingletonšŸ˜¢

Global Access Point

One of the first thing we learned about programming is to avoid Global. Because you don’t have control over it.

Whenever you leak something to the global namespace, when something is globally accessible, that thing might change without the knowledge of it. Because that thing you are interacting with anybody within the program might change that thing.

Any piece of code within your program might be able to touch that thing.

You have only a single instance

Lets see one assumption, you are thinking that in the future, you going to have only one instance. Practically its not possible when your application is growing.

Example: Consider that, you are building the chat application. It is very difficult to manage the chat rooms by using a singleton pattern. It’s impossible.

You can use singleton, when you are 100% sure that, now and future you can manage the whole application by using a single instance of a class.

Singleton make unit testing very difficult. For example: When you test the application, you can test by using one instance, you also need one more instance to mock or to differentiate that. Unfortunately you won’t get second instance by using singleton.

It’s completely fine to have a single object within your application. But it’s not fine to force to make it impossible to create a second instance. It’s not a good idea to make it impossible to create a second instance.

Because you don’t know whether you have some point actually need the second instance.

It’s completely fine to have a single object within your application, but it’s not fine to make t impossible to create a second instance. Singleton pattern with a design makes it impossible to create a second instance.

Implementation guidelines:

  1. Make the default constructor private, so that outside class cannot create the instance of our class by using new keyword.
  2. Create a static method, that acts as a constructor here. i.e, this static method calls the private constructor to create an object and saves it in a static field. All following calls to this method return the cached object.

Best real world example:

  1. Consider the president of country. He/she is the responsible for whole country. A country can have only one president.
  2. Logger example.
  3. Angular – Single page application
  4. Dependency injection.

Why do we need only one object of a class?

Objects used for logging, device drivers for printers or registry setting need to have only one of a kind. If there are multiple objects we may encounter problems like incorrect program behavior, inconsistent rules etc.

For example: Lets consider the example of printer driver, if we allow the multiple objects of printer driver created, what’s going to happen, imaging you click on file->print from power point and someone pressing file->print from ms word,there may be a lock or it gets collapsed, finally you end up with one part power point and another part word document.

To avoid these things, certain classes like Logger, print driver created with only one object.

How do we program that?

We program that by making the constructor of the particular class private and having static GetInstance() method which will check if the instance of the particular class is already there or not.

If it is already there, it will simple return it. If it is not there, it create a new object of that class and return it. How do we gain access over that method, we gain access over that, by making a method static.

Consider that, we have a Logger Class like below,

class Logger
{
    private static Logger logger;
    private Logger()
    {

    }

    public static Logger GetInstance()
    {
        if(logger == null)
        {
            logger = new Logger();
        }
        return logger; 
    }
}

Here is our driver class below,

class Program
{
    static void Main(string[] args)
    {


        //Singleton class example
        Logger obj1 = Logger.GetInstance();
        Logger obj2 = Logger.GetInstance();
        Console.WriteLine(obj1.GetHashCode());
        Console.WriteLine(obj2.GetHashCode());



        //Non Singleton example
        TestLogger objj1 = new TestLogger();
        TestLogger objj2 = new TestLogger();
        Console.WriteLine(obj1.GetHashCode());
        Console.WriteLine(obj2.GetHashCode());

    }
}

Conclusion:

If we want only one object of a class and we want to reuse the same object again and again, then it’s called a Singleton Pattern.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s