Today we will see implementation of Singleton design pattern in selenium webdriver.
Before we learn about implementation in Selenium webdriver, we must know about Singleton pattern.
Singleton Design Pattern:
When we develop a class in such a way that it can have only instance at any time, is called Singleton design pattern. It is very useful when you need to use same object of a class across all classes or framework. Singleton class must return the same instance again, if it is instantiated again.
To create a singleton class, we need to do following steps:
- Declare constructor of class as private so that no one instantiate class outside of it.
- Declare a static reference variable of class. Static is needed to make it available globally.
- Declare a static method with return type as object of class which should check if class is already instantiated once.
Look at below code snippet:
Explanation: When you run above program, you will get print “Object created.” only once while you have instantiated class twice. This is because of singleton pattern. It will not create object of class again if already initialized once.
How does Singleton pattern help in Selenium Webdriver?
- Keep track of same driver instance throughout execution.
- DBMS connectivity.
- Loading external files like properties, excel etc once rather than loading again and again.
So wherever you feel, you should have single instance of any class, you should use singleton design pattern. For example: If database connection is already established, you should not create new connection.
We will see implementation of singleton design pattern for keep track of driver.
Explanation: When you run LoadURL.java, you will see browser will be launched and url will be opened in same browser. We have instantiated two instance of class SingletonBrowserClass, but both give the same instance of driver.
If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.