Singleton Design Pattern: Boosting Code Efficiency and Performance

Simplifying Your Code with the Singleton Design Pattern

Singleton Design Pattern: Boosting Code Efficiency and Performance

Introduction

In this article, we will learn and understand the Singleton Design pattern. A design pattern is like a blueprint of software that solves a customized design problem in your code.

The singleton pattern is one of the simplest and creational design patterns. Design patterns assist developers in creating software that is more flexible, extensible, and maintainable by offering time-tested solutions to common issues.

Prerequisites

  • Any programming language.

  • Basic programming concepts.

  • Object-oriented concepts.

  • Design pattern basics. (Good to know but, Not required)

What is a singleton design pattern?

The Singleton design pattern makes sure that class can be instantiated once and can be globally accessed by all other classes throughout the application. In other words, it verifies that a class has only one instance and provides global access to that instance from anywhere in the application

The singleton design pattern reduces memory usage by sharing a single instance across the application.

Why should I use the singleton pattern?

The Singleton design pattern minimizes memory usage by sharing a single instance across the application. The Singleton design pattern is commonly used in scenarios where a single instance of an object is required to coordinate actions across multiple components or modules.

Additionally, a single resource must be shared among various components of an application. Some common use cases of the Singleton pattern include managing application configuration, logging, caching, and database connections.

What kind of problem does the Singleton Pattern solve?

The Singleton pattern can be beneficial when three conditions are met. However, these conditions may not be exhaustive for complex use cases and applications.

  • You need to manage concurrent access to a shared resource.

  • Only one instance of the object is sufficient for the entire context of the application.

  • Multiple independent sections of the application require access to the resource.

For instance, when a user logs in, the user session object can be created with the authenticated user's information. This singleton instance can then be utilized to access the user's information from various parts of the application, such as displaying the user's name and profile picture in the header, managing friend requests, updating user posts, and enforcing access control rules.

The Singleton pattern guarantees that only a single instance of the user session object is created, allowing for global access throughout the application. This centralizes control for managing user authentication information and maintains consistency across various components of the social media application.

Now, let's look into the code side of how the singleton pattern works.

Code Example Using Javascript

let instance;
let counter = 0;

class Counter {
    constructor() {
        if (instance) {
        throw new Error("You can only create one instance!");
    }
    instance = this;
}
getInstance() {
    return this;
}
getCount( ) {
    return counter;
}
increment () {
    return ++counter;
}
decrement() {
    return --counter;
}

const singletonCounter = object.freeze(new Counter());
export default singletonCounter;

The Object.freeze method ensures that consuming code cannot modify the Singleton.

Properties on the frozen instance cannot be added or altered, thus minimizing the risk of inadvertently overwriting values on the Singleton.

Here are some examples of frameworks or libraries that incorporate the Singleton pattern:

  • React Context

  • Axios

  • React Router

Pros and Cons

Let's discuss the pros and cons of the Singleton Pattern.

Pros

  • Using the Singleton pattern is beneficial when you require stricter control over global variables.

  • Eliminates the unnecessary overhead of multiple instantiations.

  • Unlike global variables, the Singleton pattern ensures that there is only one instance of a class.

Cons

  • Lack of flexibility.

  • Difficulty in unit testing.

  • Tight coupling.

Conclusion

In conclusion, the Singleton pattern is a simple yet powerful design pattern that ensures only one instance of a class is created and can be accessed globally throughout the application.

It is useful in scenarios where a single resource must be shared among various components of an application, such as managing application configuration, logging, caching, and database connections.

While there are some drawbacks to using the Singleton pattern, such as lack of flexibility and difficulty in unit testing, its benefits in reducing memory usage and providing stricter control over global variables make it a valuable tool for developers to have in their arsenal.

Thank you for reading my article. Iโ€™m going to share more tech content soon. So, Please Follow Me, Feel free to comment and share your suggestions/thoughts.

Also, Follow me on Twitter @asenseofpradhyu. I share daily Cloud, System Design, Code, and many more tech stuff ๐Ÿ˜Š

Resources

Did you find this article valuable?

Support Pradhuman Blog by becoming a sponsor. Any amount is appreciated!

ย