Skip to main content

Singleton Design Pattern in Java


Java has several design patterns Singleton Pattern being the most commonly used. Java Singleton pattern belongs to the family of design patterns, that govern the instantiation process. This design pattern proposes that at any time there can only be one instance of a singleton (object) created by the JVM. The class’s default constructor is made private, which prevents the direct instantiation of the object by others (Other Classes). A static modifier is applied to the instance method that returns the object as it then makes this method a class level method that can be accessed without creating an object.
One such scenario where it might prove useful is when we develop the help Module in a project. Java Help is an extensible, platform-independent help system that enables authors and developers to incorporate online help into applications.
Singletons can be used to create a Connection Pool. If programmers create a new connection object in every class that requires it, then its clear waste of resources. In this scenario by using a singleton connection class we can maintain a single connection object which can be used throughout the application.
 
Implementing Singleton Pattern
 
Step 1: Provide a default Private constructor
    
public class SingletonObjectDemo {
         // Note that the constructor is private
         private SingletonObjectDemo() {
          // Optional Code
        }
    }
 
Step 2: Create a Method for getting the reference to the Singleton Object
 
public class SingletonObjectDemo {
     private static SingletonObject singletonObject;
     // Note that the constructor is private
     private SingletonObjectDemo() {
          // Optional Code
     }
     public static SingletonObjectDemo getSingletonObject() {
          if (singletonObject == null) {
          singletonObject = new SingletonObjectDemo();
      }
      return singletonObject;
     }
}
 
We write a public static getter or access method to get the instance of the Singleton Object at runtime. First time the object is created inside this method as it is null. Subsequent calls to this method returns the same object created as the object is globally declared (private) and the hence the same referenced object is returned.
 
Step 3: Make the Access method Synchronized to prevent Thread Problems.
 
public static synchronized SingletonObjectDemo getSingletonObject()
It could happen that the access method may be called twice from 2 different classes at the same time and hence more than one object being created. This could violate the design patter principle. In order to prevent the simultaneous invocation of the getter method by 2 threads or classes simultaneously we add the synchronized keyword to the method declaration
Step 4: Override the Object clone method to prevent cloning

We can still be able to create a copy of the Object by cloning it using the Object’s clone method. This can be done as shown below
 
SingletonObjectDemo clonedObject = (SingletonObjectDemo) obj.clone();
    This again violates the Singleton Design Pattern’s objective. So to deal with this we need to override the Object’s clone method which throws a                 CloneNotSupportedException exception.
        public Object clone() throws CloneNotSupportedException {
                    throw new CloneNotSupportedException();
        }
The below program shows the final Implementation of Singleton Design Pattern in java, by using all the 4 steps mentioned above
class SingletonClass {

 private static SingletonClass singletonObject;
 /** A private Constructor prevents any other class from instantiating. */
 private SingletonClass() {
  //  Optional Code
 }
 public static synchronized SingletonClass getSingletonObject() {
  if (singletonObject == null) {
   singletonObject = new SingletonClass();
  }
  return singletonObject;
 }
 public Object clone() throws CloneNotSupportedException {
  throw new CloneNotSupportedException();
 }
}

public class SingletonObjectDemo {

 public static void main(String args[]) {
  //  SingletonClass obj = new SingletonClass();
                //Compilation error not allowed
  SingletonClass obj = SingletonClass.getSingletonObject();
  // Your Business Logic
  System.out.println("Singleton object obtained");
 }
}

Comments

Popular posts from this blog

How to Install SQL Server on MacOS with docker

 I'm writing a small tut for who need to install SQL Server on macOS using docker Step 1: Download the SQL Server Image sudo docker pull mcr.microsoft.com/mssql/server:2019-latest Step 2: Launch the SQL Server Image in Docker docker run -d --name example_sql_server -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=Pass.word-123' -p 1433:1433 mcr.microsoft.com/mssql/server:2019-latest Step 3: Check the SQL Server Docker Container docker ps -a Step 4: Install SQL Server Command-Line Tool sudo npm install -g sql-cli Step 5: Connect to SQL Server  5.1 Using Command mssql -u sa -p Pass.word-123 5.2: Using VSCode to connect to sql server Using the extension SQL Server (mssql)

What is API Gateway?

  What does API gateway do? The diagram below shows the detail. Step 1 - The client sends an HTTP request to the API gateway. Step 2 - The API gateway parses and validates the attributes in the HTTP request. Step 3 - The API gateway performs allow-list/deny-list checks. Step 4 - The API gateway talks to an identity provider for authentication and authorization. Step 5 - The rate limiting rules are applied to the request. If it is over the limit, the request is rejected. Steps 6 and 7 - Now that the request has passed basic checks, the API gateway finds the relevant service to route to by path matching. Step 8 - The API gateway transforms the request into the appropriate protocol and sends it to backend microservices. Steps 9-12 : The API gateway can handle errors properly, and deals with faults if the error takes a longer time to recover (circuit break). It can also leverage ELK (Elastic-Logstash-Kibana) stack for logging and monitoring. We sometimes cache data in the API gatew...