When a class is created in a way that it can have only one instance at a time, it is called Singleton Design Pattern. The singleton pattern is basically a software design pattern that restricts the instantiation of a class to one "single" instance. It is used when exactly one object is enough to coordinate within the system.
On trying to instantiate the Singleton architects' class, it returns the same instance. So, if we make any modifications inside the class through some instance, it affects the variable of the single instance created and is visible on accessing that variable with that class-type defined.
Advantages of Singleton Design Pattern
If many people have the same requirement, then it is not required to create a separate object for every requirement
Improved memory utilization
Steps to follow to create a singleton class
Declare the constructor of the class as ‘private’ so that no one can instantiate the class outside of it
Declare a static reference variable of class
Declare a static method with return type as an object of this singleton class which should check if the class is already instantiated once. The concept of Lazy Initialization will be used to create this static method.
Explanation: When you run the above program, the output would be “Object created” only once though you have created the object twice. This is because of singleton design pattern.
How does singleton design pattern help in Selenium Web driver?
Keeping track of the same driver instance throughout the execution
Loading external files like properties, excel, etc. once and not repeatedly
Logger [In logging framework, log4j property configurator and logger class instantiation can be done in singleton design pattern]
Below example is to understand the implementation of singleton design pattern with Selenium Webdriver.
Create a public class to use singleton design pattern object.
Outcome: When you run LaunchURL.java, browser get launched and opens the specified URL. We have created two instances of class SingletonBrowserClass, but both are referring to the same instance.