Singleton Design Pattern Explained – A peep into OOP

Singleton Design Pattern is a part of one of the core concepts of Object Oriented Programming. Which is Design pattern and it is a must for successful software projects. Learn when and why use Singleton Design Pattern.

Table of Contents

Introduction

Singleton Design Pattern

Every successful software project have some common way or solution that you can follow to launch your application too, design pattern is one of them. And Singleton Design Pattern is one of the popular and widely used pattern among them.

What is Design Pattern?

A solution or way of designing software. It helps solving a huge number of problems in software development. For example, maybe you are seeing some bugs with a common signature. Which you can generalize, draw them with a straight line. So your software is obviously lacking a design pattern that can solve those problems. Design pattern is actually conceptual knowledge which you can apply to create a better design.

What is Singleton Design Pattern?

Singleton design pattern is a way of designing a class. This is another usual class in your application but with one extra responsibility. It controls how many instance of the class is in the application, and to be specific there’s always only one. This is the main principle of a Singleton class.

Some consider Singleton pattern as bad OO design. Because it violates Single Responsibility Principle — one class will have one single responsibility and one responsibility only.

It uses a private constructor to construct an instance. A static public method is used to call the constructor, conventionally getInstance(). This static method checks if there is already an instance created. If not, it initializes an instance and stores the instance in a private static field. Of course this method uses the private constructor to do these. Then returns this stored instance on all subsequent calls. It is lazy initialized, if the class constructor is never called then no instance is ever created.

Only the class itself can replace the cached instance that getInstance method returns.

When to apply Singleton Pattern?

Let’s say your application is using multiple instance of a class that manages caches, registry settings, logging, device drivers etc. In this case you will run into problems including but not limited to incorrect program behavior, resources overuse etc.

Let’s consider a specific scenario, a method for database connection perhaps. Now think about it this way, your program has established a connection. You don’t need another connection to the same database. You can use the existing connection to get things done. That’s one of the scenario where Singleton class comes handy.

If you have multiple copies of these type of objects floating around then it can definitely lead to some bugs. And you will have a hard time debugging! So you must implement Singleton class to reduce or solve these type of problems.

By using Singleton class you don’t have to tell all your colleagues not to instantiate a class more than once. You can rely on the class to do this for you.

Solving Multithreading Problem

Sometimes Singleton design pattern can not handle the multithreading. You may find issues in your application — this is one of the limitations of Singleton class.

In computer architecture, multithreading is the ability of a central processing unit to provide multiple threads of execution concurrently, supported by the operating system. This approach differs from multiprocessing.

Wikipedia

You can synchronize the public static method getInstance. This will prevent two threads to enter the method at the same time.

But we need synchronization for the first time only. And synchronization is expensive, we need to think about that too. Now we can deal with this in three conventional ways.

Do nothing!

That’s right, if your performance is not affected critically by synchronizing the method. But keep in mind that it will decrease performance for sure. Maybe a part of your code that is less-traffic can produce less issue as well.

Create an Instance Eagerly

Let’s imagine a scenario where your application always create an instance of Singleton. Then you can create an instance when the class is loads. So before any thread enters the class, the instance is already there.

Double-Checked Locking

Remember what we wanted with synchronization? We wanted to synchronize the method for the first time. Because it is totally unneeded after that. By using double-checked locking we can actually achieve that. We assign a volatile keyword to the private static field that stores the instance. Then we check if any instance is there. If not, then we synchronize, for the first time only. This method can reduce your performance issue in a large scale.

volatile make sure that the variable will be handled correctly by multiple threads. Variable may be changed by multiple threads without warning.

Advantages

  • Reduces object creation expense.
  • Provides better concurrency control over shared resources.
  • Singleton class uses lazy initiation, an object is only initialized when needed. Otherwise there is no instance of the class at all.
  • Single instance will often save you some time that you would have spent debugging.

With a Singleton class you can avail strict control over global variables. Singleton is the simplest design pattern in terms of class diagram.

Limitations

  • It violates the single responsibility principle.
  • Singleton design pattern can be problematic for multithreaded environment. Then you will have take extra measure to tackle those problems.
  • It will be difficult to unit test the client code because there is no public constructor. And your test framework can definitely find it problematic to produce mock objects.

Sample Codes

If you run these codes you will see that output of the text variable will be same. Because Singleton class first created an instance on first call, but when you called the getInstance method for the second time it returned the cached instance.

Java

Singleton class,

Driver program / client code,

C#

Conclusion

No design pattern it perfect! No matter how accurate we are, we always end up with some bugs in our application. Though it cannot be perfect, but it can be improved. Look at your problems, narrow them down. And solve them step by step. Try to apply proper design patterns, which will help you some time rewriting code in your software. Plan accordingly!

Keep an eye on my blog and please let you what you think about this article on it’s discussion page.

Disclaimer: This content – Singleton Design Pattern Explained – A World of OOP and everything used in this content are copyrighted materials of S M Mahmudul Hasan, please credit properly if you are using material — image, paragraph etc.

Recommended: GitHub Tutorial – Learn GitHub Basics New to software development? Read my GitHub tutorial and learn GitHub basics — keep track of your work from creating repositories to publishing your work!