Design

Java Design Patterns: Singleton Pattern

Design thinking applied to data solutions

 Java Design Patterns

Design patterns are a well-described solution to common problems we face during software development. These solutions are obtained through experience by numerous software professionals over quite a substantial period. Hence these patterns have “evolved” rather than being “discovered”. Learning these patterns helps upcoming developers to learn software design in an easy and faster way

In 1994, four authors: Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides published a book called “Design Patterns – Elements of Reusable Object-Oriented Software” which initiated the concept of Design Pattern in Software development. These authors are collectively known as Gang of Four (GOF). The design pattern got its short name as GOF design patterns. According to these authors, design patterns are primarily based on the following principles of object orientated design.

• Program to an interface, not an implementation
• Favor object composition over inheritance

Types of Design Patterns:

There are 23 design patterns which can be classified into three categories: Creational, Structural and Behavioral patterns.
Here we will also discuss another type of design pattern called Miscellaneous/J2EE/Presentation Tier Patterns. These patterns are identified by Sun Java Centre.

1. Creational Design Pattern
The design patterns that deal with the creation of an object while hiding the creation logic, rather than instantiating objects directly using the new operator. This gives the program more flexibility in deciding which objects need to be created for a given use case.

1.1 Singleton Pattern
The singleton pattern is one of the simplest design patterns of Java.

Can we recollect what is a singleton class?

“In object-oriented programming, a singleton class is a class that can have only one object (an instance of the class) at a time.”
The purpose of the Singleton Pattern is to control object creation, limiting the number of objects to only one.
Now you know what the Singleton Design Pattern is. The next step would be to implement it.

To implement the Singleton design pattern in the Java programming language, developers need to have the following:
Static Member: It will create a single instance in the JVM memory as static are class-level variables.
Private Constructor: It will restrict the instantiation of the Singleton class from the outside world (i.e. Initialization of this class using the new keyword is prevented)
Static factory method: This provides the global point of access to the Singleton object and returns the instance to the caller

The below flow diagram gives you a clear picture of the Singleton Design Pattern

Singleton Pattern Image

Covid 19
COVID-19: Digital Insights For Enterprise Action

Access Perficient’s latest insights into how you can leverage digital technologies to not only respond to the pandemic, but drive your operations forward and deliver experiences your customers need.

Get Informed

Initialization Types of Singleton:

Singleton class can be instantiated by two methods:

1. Early initialization: In this method, the class is initialized whether it is to be used or not. The main advantage of this method is its simplicity. You initiate the class at the time of class loading. The drawback is that class is always initialized whether it is being used or not.
2. Lazy initialization: In this method, the class is initialized only when it is required. It can save you from instantiating the class when you don’t need it. Generally, lazy initialization is used when we create a singleton class.

Early initialization:

package com.creationaldesign.singleton;
public class SingletonClass {
/** Early initialization */
// create an object of SingletonClass
// Static attribute
private static SingletonClass instance = new SingletonClass();
// make the constructor private so that this class cannot be
// instantiated
// Note: Singleton pattern restricts the instantiation of a class and ensures
// that only one instance of the class exists in the Java virtual machine
// Private constructor
private SingletonClass() {
}
// Get the only object available
// Static function
public static SingletonClass getInstance() {
return instance;
}
public void showMessage() {
System.out.println("This is the message from the Singleton Class");
}
}

Here we have created an instance of Singleton in a static initializer. JVM executes static initializer when the class is loaded. Use this method only when your singleton class is light and is used throughout the execution of your program.

You can also go for a better approach “Double-checked locking
“Double-checked locking”:
If you notice carefully once an object is created synchronization is no longer useful because now obj will not be null and any sequence of operations will lead to consistent results.

So we will only acquire a lock on the getInstance() once when the obj is null. This way we only synchronize the first way through, just what we want and hence this is guaranteed to be thread-safe.

Lazy initialization:

package com.creationaldesign.singleton;
/**
* Double Checked Locking based Java implementation of singleton design pattern
* This is clearly mentioned in https://en.wikipedia.org/wiki/Singleton_pattern
* under Lazy Initialization
*/
public class SingletonClass {
// Static and Volatile attribute
private volatile static SingletonClass obj;
// Private constructor
private SingletonClass() {
}
// Static function
public static SingletonClass getInstance() {
if (obj == null) {
// To provide thread-safe implementation
synchronized (SingletonClass.class) {
// check again as multiple threads can reach above step
if (obj == null)
obj = new SingletonClass();
}
}
return obj;
}
}

We have declared the obj volatile which ensures that multiple threads offer the obj variable correctly when it is being initialized to Singleton instance. This method drastically reduces the overhead of calling the synchronized method every time.

In any of the two (Early/Lazy Initialization) methods create a class. Then create the main method to test the Singleton class as below,

Main Method:

package com.creationaldesign.singleton;
/**
* Singleton Pattern Main Class!
*
*/
public class SingletonPatternApp {
public static void main(String[] args) {
// illegal construct of the singleton class
// Compile Time Error: The constructor SingleObject() is not visible
// SingletonClass newObjInstance = new SingletonClass();
// Get the only object available
SingletonClass getOldInstance = SingletonClass.getInstance();
// show the message
getOldInstance.showMessage();
}
}

Console Output:
This is the message from the Singleton Class

Class Diagram:

Singleton Pattern Class Diagram

Let us see some of the Examples of Singleton class:

1) java.lang.Runtime: Java provides a class Runtime in its lang package which is Singleton in nature.
2) java.awt.Desktop: The Desktop class allows a Java application to launch associated applications registered on the native desktop to handle a URI or a file. This class also cannot be instantiated from the application. Hence it is also a Singleton class.
3) cache-memory
4) database connection
5) drivers
6) logging
7) Hardware access
8) Config files

 

About the Author

More from this Author

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Subscribe to the Weekly Blog Digest:

Sign Up
Categories