• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

SoftwareTestingo - Interview Questions, Tutorial & Test Cases Template Examples

SoftwareTestingo - Interview Questions, Tutorial & Test Cases Template Examples

  • Home
  • Test Case Examples
  • Interview Questions
  • Interview Questions Asked
  • Java
  • Java Program
  • Selenium
  • Selenium Programs
  • Manual Testing
  • Difference
  • Tools
  • SQL
  • Contact Us
  • Search
SoftwareTestingo » Selenium » Free Selenium Tutorial » What is Singleton Class Java & How to implement With Selenium WebDriver?

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

Last Updated on: April 19, 2019 By Softwaretestingo Editorial Board

What We Are Learn On This Post

  • How to create our own Singleton Class?

Singleton Class Java: For any java class if we are allowed to create only one object such type of class 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 in selenium with real-time example.

Advantages: if several peoples have the same requirement then it is not recorded to create a separate object for every requirement.

we have to create only one object and we can reuse the same object for every similar requirement is that the performance and the memory utilization will be improved.

How to create our own Singleton Class?

we can create our own singleton classes for this we have to use the private constructor, private static variable and public factory method.

Design Pattern 1

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

SingletonDesignDemo1.Java

package com.softwaretestingblog.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.softwaretestingblog.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 by using the above method but there is a drawback of this method. in the above method, we create the object irrespective of it’s 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.

You Can see the Full image using this link

Note: Runtime class is internally implemented by using this approach.

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 below example in the main class then we call the below statement

SingletonDesignDemo2 obj = SingletonDesignDemo2.getObject();

It will instance and verify if the instance is null or not. if that instance is already initialized then 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.softwaretestingblog.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.softwaretestingblog.singleton;
public class SingletonDesignMain2 
{
   public static void main(String[] args) 
   {
      // TODO Auto-generated method stub
      SingletonDesignDemo2 obj = SingletonDesignDemo2.getObject();
      obj.demoMethod();
   }
}

At any point in time for the test class, we can create only one object. Hence Test class is Singleton class. See the full image use this link

How to Implement Singleton Class with Selenium WebDriver?

ConstantVariable.java

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

BaseClass.java

package com.softwaretestingblog.singleton;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Baseclass 
{
   public static WebDriver driver=null;

   public static void initilize()
   {
      //Use Of Singleton Concept and Initilize webDriver
      if(driver == null)
      {
         if(ConstantVariable.browserName.equalsIgnoreCase("chrome"))
         {
            System.setProperty("webdriver.chrome.driver", "F:\\Photon_Workspace\\SingletonPracticeProject\\Drivers\\chromedriver.exe");
            driver=new ChromeDriver();
         }
         else if(ConstantVariable.browserName.equalsIgnoreCase("Firefox"))
         {
            System.setProperty("webdriver.gecko.driver", "F:\\Photon_Workspace\\SingletonPracticeProject\\Drivers\\geckodriver.exe");
            driver=new FirefoxDriver();
         }
         else if(ConstantVariable.browserName.equalsIgnoreCase("IE"))
         {
            System.setProperty("webdriver.edge.driver", "F:\\Photon_Workspace\\SingletonPracticeProject\\Drivers\\MicrosoftWebDriver.exe");
            driver=new EdgeDriver();
         }
      }
      
      //Perform Basic Operations
      driver.manage().deleteAllCookies();
      driver.manage().window().maximize();
      driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
      driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
   }
   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.softwaretestingblog.singleton;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestClass 
{
   @BeforeClass
   public void setup()
   {
      Baseclass.initilize();
   }
   @Test
   public void openUrl() throws InterruptedException
   {
      Baseclass.openurl(ConstantVariable.URl);
      Thread.sleep(3000);
   }
   @AfterClass
   public void tearDown()
   {
      Baseclass.quit();
   }
}
[RemoteTestNG] detected TestNG version 6.14.2
Starting ChromeDriver 2.41.578737 (49da6702b16031c40d63e5618de03a32ff6c197e) on port 49070
Only local connections are allowed.
Sep 21, 2018 10:51:31 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
PASSED: openUrl

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

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

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

    Filed Under: Free Selenium Tutorial

    Reader Interactions

    Comments

    1. Avatar for parthapartha says

      September 21, 2018 at 10:21 AM

      in baseClass.java line no:30 , needs to be changed.

      Reply
      • Avatar for SoftwareTesting BlogSoftwareTesting Blog says

        September 21, 2018 at 10:54 AM

        Thanks, Partha For report the error… we have updated that

        Reply
    2. Avatar for jamesjames says

      November 9, 2018 at 1:28 PM

      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
      • Avatar for SoftwareTesting0SoftwareTesting0 says

        January 30, 2019 at 8:21 AM

        Thanks, James We try to add more such type of articles in our blog

        Reply
    3. Avatar for Automation testerAutomation tester says

      October 30, 2019 at 9:25 PM

      It is really a good article. But I have a question. Where is the Private constructer in the Base class?

      Reply
    4. Avatar for TSTS says

      November 21, 2019 at 11:14 AM

      How does the singleton class control when driver.quit() and driver.close() are called?

      Reply
    5. Avatar for umesh karkarumesh karkar says

      June 4, 2021 at 10:52 PM

      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 Reply Cancel reply

    Your email address will not be published. Required fields are marked *

    Primary Sidebar

    Join SoftwareTestingo Telegram Group

    Categories

    Copyright © 2023 SoftwareTestingo.com ~ Contact Us ~ Sitemap ~ Privacy Policy ~ Testing Careers