Introduction to Creational Design Patterns

Singleton Implementation - Episode 01

Fig 1 : Design Patterns

The reusable solution to any commonly occurring problem is known as Design Pattern. Design Patterns are mostly practiced in this programming world.

Now, you may thing what is commonly occurring problem? Let’s see with an example.

Example:
If we require only one instance to be created from a class and other classes can use that object.

Solution:
The best solution is Singleton design pattern. And, all other design patterns will have a set of rules and specifications to solve problems. We will learn them one by one.

We have remember that these design patterns are independent to programming languages. So, design pattern is an idea, not an implementation. They are used to solve any commonly occurring object-oriented problems. We can make our implementation more maintainable, reusable and flexible by using design patterns in our project. Java follows design patterns internally. If you want to become a professional, you must know some popular solutions like design patterns to implement your program.

Advantage of design pattern:

  1. The solutions can be reused.
  2. Make the design of application transparent.
  3. Design Pattern solutions are well testified and proved solutions because that have been built by expert developers.
  4. They helps in defining the architecture of the system.
  5. They are not an absolute solution. But they provide clarity to built a better system.

Creational Design Patterns

Fig 2: Creational Design Patterns

Creational design patterns are used in defining the way of creating objects for the class. A decision has to be taken during the time of object instantiation. But, we know that new keyword is used to create a new object. Foe example

Object obj = new Object();

Hard-Coded code is not appropriate for programming. Here, new keyword is used to create a new instance. The nature of the object may be differ based on the programming. Creational Design Patterns can be used to make this scenario flexible and general.

Types of creational design patterns

Types of Creational Design Pattern are as follows: Singleton, Multiton, Object Pool, Factory, Factory Method and Abstract Factory.

But, we will have an introduction to Singleton pattern and its implementation in this article.

Singleton

Singleton pattern is one of the simplest design patterns in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.

Singleton Design Pattern deals with a class that is responsible in creating a new object while ensuring that only one object gets created.

This pattern involves a single class which is responsible to create an object while making sure that only single object gets created. This created object can be accessed directly rather than instantiating the object.

“define a class that has only one instance and provides a global point of access to it”

To say simply, the pattern ensures that a single object should be instantiated and that object cab be used by all other class.

Pros of Singleton design pattern

  • Helps to save memory as the object is not created for every request. Only one object is created and accessed repeatedly.

Applications of Singleton design pattern

  • Used in database and multi-threaded applications. It is used in thread pools, configuration settings, caching, logging etc.

The implementation of Singleton can be discussed under following topics:

  • Early Instantiation (creating instance at load time)
  • Lazy Instantiation (creating instance when required)
  • Thread Safe Singleton Implementation
  • Double Checked locking Singleton Implementation
  • Bill Pugh Singleton Implementation

Understanding early Instantiation of Singleton Pattern

In this case, we initialize an instance at the time of declaring the static variable. Therefore, the instance is created at the time of loading the class.

Let’s see an example for designing singleton implementation for early instantiation.

class Singleton{
private static Singleton singleton=new Singleton();
private Singleton(){
//Constructor
}
public static Singleton get_Singleton(){
return singleton;
}
}

Pros : Can be implemented easily.

Cons: Resource may be wasted. Some of the objects may not be required.

Understanding lazy Instantiation of Singleton Pattern

In this case, instance is created in the synchronized method or block, the instance van be created when required.

Let’s see an example for designing singleton implementation for lazy instantiation.

class Singleton{
private static Singleton singleton;
private Singleton(){
//Constructor
}
public static Singleton get_Singleton(){
if (singleton == null){
singleton = new Singleton();
}
return singleton;
}
}

Pros: Instance is created at user request. It can reduce resource and CPU wastage.

Cons: Overhead of checking the null condition every time in multithreaded environment.

Thread safe Singleton Implementation:

We can use the global access method synchronized to implement a thread-safe Singleton class. Therefore, only one thread can execute this method at a time.

The easier way to create a thread-safe singleton class is to make the global access method synchronized, so that only one thread can execute this method at a time. General implementation of this approach is like the below class.

public class ThreadSafeSingleton {
private static ThreadSafeSingleton instance;
private ThreadSafeSingleton(){}
public static synchronized ThreadSafeSingleton getInstance(){
if(instance == null){
instance = new ThreadSafeSingleton();
}
return instance;
}
}

Thread-safe implementation provides thread-safety but this may cause the performance to reduce. Additional cost will be created with the synchronized method. Only one thread may create the instance, but all threads wait for synchronized method every time they need instance. To avoid this overhead, double checked locking can be used. This method includes an additional check inside synchronized method. This ensures that only one instance is created from the class.

Double Checked Locking Implementation:

public final class Singleton {
private static volatile Singleton instance;

private Singleton() {}

public static Singleton getInstance(String value) {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}

Pros: Threat safe, Lazy initialization, Reduce Performance overhead.

Cons: Performance is affected in the first time.

Bill Pugh Singleton Implementation

Prior to Java 5, the Java memory model had a number of difficulties, and the above methods used to fail in certain situations where too many threads are attempting to get the Singleton class instance concurrently. So Bill Pugh came up with a new approach to constructing a singleton class using an inner static helper class. Let’s see the implementation of Bill Pugh Singleton:

public class BillPughSingleton {
private BillPughSingleton(){}
private static class Singleton Helper{
private static final BillPughSingleton INSTANCE = new BillPughSingleton();
}

public static BillPughSingleton get Instance(){
return SingletonHelper.INSTANCE;
}
}

Out of these implementations, we have to know when to use what.

  1. It is easy to implement Eager initialization but it may waste CPU time and resource. Use this only if your program will require the instance.
  2. Synchronized implementation can be used in multi-threaded environment but it may reduce the performance. Double checking lock principle can be used instead.
  3. Bill Pugh implementation is most widely used approach for singleton classes. Most developers prefer it because of its simplicity and advantages.

I hope this article helps you in grasping fine details of Singleton design pattern, do let me know through your thoughts and comments. We would discuss other design patterns in the following articles.

Reference

[1] https://www.geeksforgeeks.org/java-singleton-design-pattern-practices-examples/

[2] https://www.geeksforgeeks.org/singleton-class-java/

[3] https://sourcemaking.com/design_patterns/singleton

Undergraduate, Computer Science & Engineering

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store