What is Singleton Class Java & How to implement With Selenium WebDriver?

Singleton Class Java: For any Java class, if we can create only one object, such class type is called a singleton class. So, in this post, we will try to discuss more singleton design patterns or Singleton class, and we will also try to implement them in Selenium with real-time examples.

Advantages: if several people have the same requirement, creating a separate object for every requirement is not recommended.

we have to create only one object, and we can reuse the same object for every similar requirement to improve performance and memory utilization.

How do we create our own Singleton Class?

we can create our singleton classes for this, and we must use the private static variable and public factory method.

Singleton Design Pattern 1

In this Pattern, you can see that we are creating an instance much before its requirement. In most cases, it is done in the system startup; that’s why it is called an eager initialization singleton pattern.

SingletonDesignDemo1.Java

package com.softwaretestingo.singleton;
public class SingletonDesignDemo1 
{
   private static SingletonDesignDemo1 obj=new SingletonDesignDemo1();
   
   //We Make Constructor as Private so other class will not create object
   private SingletonDesignDemo1()
   {
      
   }

   public static SingletonDesignDemo1 getObject()
   {
      return obj;
   }
   
   //Other Method protected by Singleton-ness
   public static void demomethod()
   {
      System.out.println("Singleton Design Pattern Method 1");
   }

}

SingletonDesignMain1.Java

package com.softwaretestingo.singleton;
public class SingletonDesignMain1
{
   public static void main(String[] args) 
   {
      // TODO Auto-generated method stub
      SingletonDesignDemo1 obj= SingletonDesignDemo1.getObject();
      obj.demomethod();
   }
}

We can create a singleton class using the above method, but this method has a drawback. in the above method, we create the object whether required or not.  if the instance is not a big object and you can live with it being unused, then it is the best approach.

Note: The runtime class is internally implemented using this approach.

Singleton Design PatternĀ  2:

In this design pattern, you can say that we are not creating the instance before its requirement. As you see in the example below, we call the statement below in the main class.

SingletonDesignDemo2 obj = SingletonDesignDemo2.getObject();

It will identify and verify if the instance is null or not. if that instance is already initialized, it will allow you to initialize again. In this way, we are implementing the singleton design pattern here. if the instance is not initialized, then it will proceed further and initialize the instance.

SingletonDesignDemo2.java

package com.softwaretestingo.singleton;
public class SingletonDesignDemo2 
{
   private static SingletonDesignDemo2 obj=null;	
   //We Make Constructor as Private so other class will not create object
   private SingletonDesignDemo2()
   {
      
   }	
   public static SingletonDesignDemo2 getObject()
   {
      if(obj==null)
      {
         obj= new SingletonDesignDemo2();
      }		
      return obj;
   }	
   public static void demoMethod()
   {
      System.out.println("Singleton Design Pattern Method 2");
   }
}

SingletonDesignMain2.Java

package com.softwaretestingo.singleton;
public class SingletonDesignMain2 
{
   public static void main(String[] args) 
   {
      // TODO Auto-generated method stub
      SingletonDesignDemo2 obj = SingletonDesignDemo2.getObject();
      obj.demoMethod();
   }
}

We can create only one object at any time for the test class. Hence, the Test class is the Singleton class.

How do you implement Singleton Class with Selenium WebDriver?

ConstantVariable.java

package com.softwaretestingo.singleton;
public class ConstantVariable 
{
	public static String browserName = "Chrome";
	public static String URl = "https://demo.softwaretestingo.com/";
}

BaseClass.java

package com.softwaretestingo.singleton;
import java.time.Duration;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class TestBase 
{
	public static WebDriver driver=null;
	   public static void initilize()
	   {
	      //Use Of Singleton Concept and Initilize webDriver
	      if(driver == null)
	      {
	         if(ConstantVariable.browserName.equalsIgnoreCase("chrome"))
	         {
	            driver=new ChromeDriver();
	         }
	         else if(ConstantVariable.browserName.equalsIgnoreCase("Firefox"))
	         {
	            driver=new FirefoxDriver();
	         }
	         else if(ConstantVariable.browserName.equalsIgnoreCase("IE"))
	         {
	            driver=new EdgeDriver();
	         }
	      }
	      
	      //Perform Basic Operations
	      driver.manage().deleteAllCookies();
	      driver.manage().window().maximize();
	      driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));
	      driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(30));
	   }
	   public static void quit()
	   {
	      driver.quit();
	      driver=null; // we destroy the driver object after quit operation
	   }
	   public static void close()
	   {
	      driver.close();
	      driver=null;  // we destroy the driver object after quit operation
	   }   
	   public  static void openurl(String URL)
	   {
	      driver.get(URL);
	   }
}

TestClass.java

package com.softwaretestingo.singleton;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class SingletonClass 
{

	@BeforeMethod
	public void setup()
	{
		TestBase.initilize();
	}
	@Test
	public void openUrl() throws InterruptedException
	{
		TestBase.openurl(ConstantVariable.URl);
		Thread.sleep(3000);
	}
	@AfterMethod
	public void tearDown()
	{
		TestBase.quit();
	}
}

The Console Output Will Be

[RemoteTestNG] detected TestNG version 7.8.0
Feb 07, 2024 1:51:02 PM org.openqa.selenium.devtools.CdpVersionFinder findNearestMatch
WARNING: Unable to find an exact match for CDP version 121, so returning the closest version found: 117
PASSED: com.softwaretestingo.singleton.SingletonClass.openUrl

===============================================
    Default test
    Tests run: 1, Failures: 0, Skips: 0
===============================================


===============================================
Default suite
Total tests run: 1, Passes: 1, Failures: 0, Skips: 0
===============================================

Still, if you have any doubts about the implementation Of Selenium Webdriver, then drop your query in the comment section.

Avatar for Softwaretestingo Editorial Board

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

7 thoughts on “What is Singleton Class Java & How to implement With Selenium WebDriver?”

  1. Nyc article about singleton class hope more article will be on the way. the way you describe in this article is oosum like subjective,example and with live implementation

    Reply
  2. Nice article but have one question, how can we run test cases sequentially. E.g. if we have another testclass with one test case then how can we run these two test classes(with one test case in each class) ?

    Reply

Leave a Comment