Design Pattern #1 Singleton Pattern

Design Pattern #1 Singleton Pattern

Design patterns are one of the most used solutions to improve a framework or code structure. Singleton pattern is part of creational patterns and deals with how an object is going to be created.

How Singleton pattern works?

By using this design pattern we focus on creating exactly one copy of class object. This one copy will now be shared with other classes if needs to be used again.


How can you incorporate Singleton Pattern?

  1. Create a private static instance of the class
  2. Create a private constructor of the class (to precent object creation outside)
  3. Create public static method to get instance of the class or target object


Different ways to setup Singleton Pattern

1. Eager Initialisation

Using eager initialisation an instance of a class is created much before it is actually required. It is mostly done on system startup.

The singleton instance is created irrespective of whether any other class actually asked for its instance or not. This is done usually using a static variable as these get initialised at the application startup, always.

public class EagerSingleton {

	private static volatile EagerSingleton instance = new EagerSingleton();

	// private constructor
	private EagerSingleton() {
	}

	public static EagerSingleton getInstance() {
	return instance;
	}
}        

The above method works fine, but it has one drawback. The instance is created irrespective of it is required in runtime or not.


2. Lazy Initialisation

Lazy initialisation is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until it is needed the first time.

In the context of the singleton pattern, lazy initialisation restricts the creation of the instance until it is requested for the first time.

public class LazySingleton {

	private static  LazySingleton instance = null;

	// private constructor
	private LazySingleton() {
	}

	public synchronized static LazySingleton getInstance() {
		if (instance == null) 
               {
			instance = new LazySingleton();
		}
		return instance;
	}
}        

The above code works fine until we are using it with sequential execution, but the moment we move it into a Multi-Threaded Env. or Parallel execution. This setup fails and delays the execution.

Why does this delay occur?

As you can see in above code, we have used synchronized keyword in our method declaration, which means whenever a thread reaches this method 2 things will happen:

  1. If thread-1 is already using this method then thread-2 need to wait until the completion of thread-1 task
  2. If thread-2 starts and then thread-3 needs wait, vice-versa

Which in turn delays the execution, hence to improve this performance we are going to use a synchronized block.


Updated Code:

public class LazySingleton {

	private static volatile LazySingleton instance = null;

	// private constructor
	private LazySingleton() {
	}

	public static LazySingleton getInstance() {
		if (instance == null) {
			synchronized (LazySingleton.class) {
				// Double check
				if (instance == null) {
					instance = new LazySingleton();
				}
			}
		}
		return instance;
	}
}        

Now with above code, if instance is null then only it enters the synchronized block and otherwise it will just return the instance without any delays.


I hope this makes easier for you to understand and implement singleton pattern into your frameworks. If you like such articles the consider subscribing to my newsletter link below. Also share it within your network if possible :)

Subscribe to newsletter: Link

SDET Manager Course: Link

Full Stack QA Course: Link

950+ SDET Interview Questions with Answers: Link


#japneetsachdeva

Clint Engler

CEO/Principal: CERAC Inc. FL USA..... ?? ????????Consortium for Empowered Research, Analysis & Communication

4 个月

Very helpful

要查看或添加评论,请登录

Japneet Sachdeva的更多文章

  • What is a bug? | Everything about Bugs a QA should know!

    What is a bug? | Everything about Bugs a QA should know!

    First thing first, let's quickly define it and jump to real world picture understanding A bug is an error or flaw in an…

  • Complete Front End Testing Guide for 2025

    Complete Front End Testing Guide for 2025

    Front End Testing is crucial for delivering a high quality product which functions well and meets user expectations…

    2 条评论
  • Earn 1 Lakh per month using Generative AI | No Clickbait

    Earn 1 Lakh per month using Generative AI | No Clickbait

    The actual possibility to create a side-income in 2025 is really true. If you know "How to generate value" then…

    3 条评论
  • Selenium WebDriver Classic vs Selenium WebDriver BiDi

    Selenium WebDriver Classic vs Selenium WebDriver BiDi

    WebDriver BiDi overview for Test Automation Engineers who interact with Web Browsers, Test Web Apps and Plan for the…

    5 条评论
  • AI Assisted Testing | AI Powered Testing | AI Agents for Testing

    AI Assisted Testing | AI Powered Testing | AI Agents for Testing

    Instead of using complicated terms, let's keep it simple. It's nothing but AI-Driven Testing.

    2 条评论
  • Decoding Test Pyramid for Upcoming SDETs

    Decoding Test Pyramid for Upcoming SDETs

    Software testing is a complicated process, until we figure out what can be automated and what should be kept as part of…

    3 条评论
  • State Transition Testing

    State Transition Testing

    ISTQB definition: State transition testing (finite state testing) - a black-box test technique using a state transition…

    2 条评论
  • Chaos Monkey Tests by Netflix

    Chaos Monkey Tests by Netflix

    Netflix uses a technique or say system which purposefully throws it or breaks it in production or replicated production…

    1 条评论
  • How to approach APIs for exploratory Testing?

    How to approach APIs for exploratory Testing?

    Top API Testing Tools for 2025 Postman Bruno Insomnia Swagger Why API's Exploratory Testing is required? Early adoption…

    3 条评论
  • Top 4 API Authentications we should know!

    Top 4 API Authentications we should know!

    Application Programming Interface (API) the vital links that allow applications to exchange services and data—require…

    5 条评论