Design Patterns — A quick guide to Singleton pattern.

Andreas Poyias
5 min readDec 17, 2018

--

This is another quick-guide to mastering a very commonly used design pattern, the Singleton pattern. Singleton pattern is one of the simplest but most controversial design patterns (with pros and many cons). This is one of the main reasons why it is very common in programming interviews.

Singleton pattern is classified in the creational design patterns which is all about class/object instantiation. More precisely, how to effectively use inheritance (class-creation patterns) or delegation (object-creation patterns). [by Design Patterns explained simply]

Singleton definition: In mathematics, is defined as “a set which contains exactly one element”. This pattern is very simple to understand and easy to implement since it is only a few lines of code and the application is quite straight-forward. It is a pattern that ensures a class has only one instance and provides a global point of access to it. For example, we can only have one active Pope of Italy, therefore, it is possible that the Pope can be represented with a Singleton pattern.

Step 1 — Keywords

Defining keywords is the secret recipe in this series of quick-guides. This method helped me truly understand the design patterns, hardcode them in my mind and comprehend the differences among other design patterns.

This time the keywords take us a trip back to basics. It is an introduction to the very simple code that will follow. Feel free to skip to the next step if you feel comfortable with the terms.

  1. Class-instance: An instance is a concrete occurrence of any object. It exists usually during the runtime of a computer program and it emphasizes in distinctly identifying the object. Similarly, class-instances are created from classes by subroutines like constructors/destructors.
  2. Private Constructor: A private constructor is a special instance constructor. It is generally used in classes that contain static members only. If a class has one or more private constructors and no public constructors, then other classes (except nested classes) are not allowed to create instances of this class.
  3. Static data members: When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member. [from TutorialPoint]
  4. Static Function: A static member function can be called even if no objects of the class exist. [from TutorialPoint]

Step 2 — Diagram

There are one-two programming tricks to make a class Singleton. Other than that it is quite trivial. Reading the diagram from top to bottom: We should have

  • A static(underlined) and private(-) instance of the class
  • A private constructor.
  • A public(+) and static function that returns the instance.

Class definition should not be more than 7–8 lines of code, depending on the programming language.

Step 3 — Code by example

I suggest to copy the code class by class from my git repository “Andreas Poyias” or from the snippets here and paste it in any of the available online C++ editors like c++shell, jdoodle , onlineGDB and run it to observe the output. Then read the comments or description below.

Class definition
I am showing the class definition in C++ which is 8 lines of code.

#include <iostream>class Singleton
{
public:
static Singleton *getInstance();
private:
Singleton(){}
static Singleton* s_instance;
};

Now we move on to the declaration of the getInstance()method and the static data member which is outside the class definition. There are different ways to write the getInstance function. For simplicity, I chose the one shown in the snippet below. So if the instance does not exist, instantiate one if it does exist then just return it.

Singleton* Singleton::s_instance = 0;Singleton* Singleton::getInstance()
{
if(!s_instance) {
s_instance = new Singleton();
std::cout << "There is no instance so we created one.\n";
return s_instance;
}else{
std::cout << "Hey this is the same instance!\n";
return s_instance;
}
}

Main function
The main function operates as the client. The client cannot create a second instance of theSingletonclass and is forced to use the existing one. This can be displayed by the output as well.

int main()
{
Singleton *singlA = Singleton::getInstance();
Singleton *singlB = Singleton::getInstance();
return 0;
}
// Output
// There is no instance so we created one.
// Hey this is the same instance!

There are a few benefits for the use of Singleton pattern. Other design patterns like Abstract Factory, Facade can use Singleton pattern (usually only one Facade object is required). As I mentioned in the first paragraph this design pattern is quite controversial and that is why a popular interview question is: “what is wrong with Singleton pattern, or why is Singleton pattern considered anti-pattern?”

Anti-pattern
I will summarise the reasons why singleton is considered anti-pattern. There is a very popular discussion on StackOverflow which provides really good justice justifying why one should be careful with this design pattern.

  1. Singleton patterns violate the single responsibility principle: by virtue of the fact that they control their own creation and lifecycle.
  2. They are generally used as a global instance which may lead to hidden dependencies in the code that could be exposed via interfaces.
  3. They inherently cause code to be tightly coupled.
  4. It is very difficult to adjust Singleton pattern in a multithreading environment and very easy to fall into race condition problems during initialization.

For deeper understanding as to why this is considered anti-pattern, have a look in this site by Michael Safyan.

Since we mentioned it above, the next blog will be a quick guide to the Facade design pattern. The Facade is not a creational pattern like Singleton and Abstract Factory but is classified as a structural design pattern. Don’t forget to like/clap my blog-post and follow my account. This is to give me the satisfaction that I helped some fellow developers and push me to keep on writing.

Other quick-guides on design patterns:

  1. Design Patterns — A quick guide to Abstract Factory.
  2. Design Patterns — A quick guide to Bridge Pattern.
  3. Design Patterns — A quick guide to Builder Pattern.
  4. Design Patterns — A quick guide to Decorator Pattern.
  5. Design Patterns — A quick guide to Facade Pattern.
  6. Design Patterns — A quick guide to Observer Pattern.
  7. Design Patterns — A quick guide to Singleton Pattern.

--

--

Andreas Poyias

PhD in the development of data mining algorithms. I am a proud nerd that loves technology!