Skip to content
APPCITORThe Tech Blog
Esc

Creational – Singleton Design Pattern

July 25, 2020 2 min read

Creational – Singleton Design Pattern

Design pattern is a solution that provides for a common software problem. Those are very popular among software developers.

There are 23 design patterns that can be classified in to 3 parts.

  1. Creational Patterns
  2. Structural Patterns
  3. Behavioral Patterns

Let’s learn about the Creational Design Patterns first. For that I am going to take the Singleton Design Pattern which comes under Creational Design Pattern category.

Singleton Design Pattern

“The Singleton Design Pattern means a pattern that restricts the instantiation of a class to one object.”

It is one of the easiest design patterns that use by software developers. Here we give only one chance to create an object for the class that is made by the user. That means in every time that user refers an object, we give only one static object to use.

Let’s see go with an example.

Here the class that I made is called “oneObject”. In 1st line I made a constructor by the class name. Normally a constructor is public. But here I used private. It means we can’t make objects by this class name in outside of the class.

In 2nd line I made an object that is static by calling the constructor made in the 1st line using “new” keyword. Also the object variable “instance” cannot access by outside of the class as it is private.

See the 3rd line. There I called the method “getInstance()” that is public to return the object variable ”instance”.

I used the code in 4th line to check the program is running or not.

Let’s go to the main method of the above class.

Here in 1st line I tried to call the oneObject constructor that is made in the class above. But it gives a compile error because the constructor that I made in the class is private. Therefore in 2nd line I tried to call the getInstance() method in the class because it is public and static. Here the thing happened is I used the same object to call the static method that I wanted without creating a new object.

Therefore if you want to make any object out of the class, you can use the same object that you made in the class without creating new objects again and again. This is an advantage of singleton design pattern.

Let’s discuss about singleton design pattern furthermore with a real example.

The best example is the establishing of JDBC Connection in a software. Let’s assume that we create a DBConnection class. It contains private constructor as well as a private static instance. Then DBConnection class provides a static method to get its static instance to the outside of the class. Now any of the class you create can use DBConnection class to get the DBConnection object.

Hope you got better understand about Singleton Design Pattern.

Thank you.

Share this article

Keep reading