Singleton Design Pattern

Tushar Ghosh
2 min readFeb 5, 2023

--

UML of Singleton Design Pattern

Singleton design pattern is the simplest design pattern that will have only one instance of class in the entire application. It can be access globally. It belongs to the “Creational Design Pattern”.

Key features:

  • Increased Performance: Singleton ensure one instance of a class, so its reduce the overhead the multiple instance. It require less memory.
  • Single Point of Control: Singleton pattern provides a single point of control that make the system easy to maintain.

Real Example:

  • Database connection : A database connection manager (Like: JDBC) ensures that only one connection to a database and provides a single point of access to that connection in the application.
  • Configuration Manager: A configuration manager is a good example of the singleton pattern. The configuration manager ensures that only one instance of the configuration.
  • Logging: A logging system is another example of the singleton pattern

Singleton Pattern Implementation in Java:

Singleton pattern can be implemented many different way. But I will discuss two easy different way.

Eager initialization:

Eager instantiation refers to the creation of an instance of an object as soon as it is declared. In the case of a singleton, an eager singleton is created when the class is loaded.

Lazy initialization:

A lazy instance of a singleton is a design pattern in which the singleton instance is created only when it is first requested.

Singleton in Multiple Threads:

We can run the singleton in multiple threads. In main method, create a 10 threads to create the singleton object. In the output, we can see, different hashcode generated. The test shows that threads are creating multiple instances of the Singleton class. The test “instance == null” is being interrupted so that it appears to be true to more than one thread and so the constructor is called multiple times(We have a ‘race’ condition).

Output of the multiple threads

We can force threads to access the getInstance method of Singleton one at a time by labeling getInstance with the keyword synchronized

synchronized public static Singleton getInstance() {

// To do

}

References:

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Tushar Ghosh
Tushar Ghosh

Written by Tushar Ghosh

MEAN | JavaScript | Node.js | React| Angular | Frontend

No responses yet

Write a response