Skip to main content

Command Palette

Search for a command to run...

Singleton Design Pattern

Updated
5 min read
Singleton Design Pattern

Introduction

Hello all, today I back with another Design Patterns topic, and today I will share what i learned about Singleton design pattern. I hope with this article you will know more about Singleton design pattern and use it on your project.

What It Is?

The Singleton design pattern is a creational pattern that ensures a class has only one instance throughout the application's lifecycle. By providing global access to this instance, the pattern allows developers to easily retrieve and use the same instance whenever needed.

When To Use It?

Here are some scenarios where implementing the Singleton design pattern can be beneficial to a project:

  • When a single access point is essential for managing a shared resource or configuration, the Singleton design pattern ensures that only one instance is created and accessed throughout the application.

  • When multiple components need to access and share the same state or resource, such as a database connection or configuration setting, the Singleton design pattern provides a consistent and controlled way to manage that shared resource.

  • When managing limited resources, such as a thread pool or connection pool, the Singleton design pattern ensures efficient resource allocation while preventing resource exhaustion.

Why Implement It?

Here are some pros and cons to consider before implementing the Singleton design pattern in a project:

Pros

  • Guarantees only one instance of a class exists, avoiding conflicts or duplication.

  • Provides a single point of access to the instance across the application.

  • Simplifies the handling of shared global state within the application.

  • Reduces resource consumption by avoiding multiple instances.

Cons

  • Violates the Single Responsibility Principle.

  • Can lead to race conditions in multi-threaded environments.

  • Can lead to hidden dependencies and make the code harder to maintain.

  • Can lead to tight coupling between components, making the code less flexible and harder to modify.

How To Implement It?

Here are the steps to implement the Singleton design pattern in a project:

  1. Create a private constructor for the Singleton class to prevent other classes from creating instances of the Singleton class.

  2. Create a private static variable that will hold the instance of the Singleton class to ensures that only one instance exists.

  3. Create a public static method that returns the instance of the Singleton class. This method should check if the instance is null and create a new instance if it’s null to ensure controlled access to the single instance.

Structure

Pseudocode

BEGIN CLASS Singleton
    PRIVATE STATIC FIELD instance : Singleton

    BEGIN PRIVATE CONSTRUCTOR Singleton
    END CONSTRUCTOR

    BEGIN PUBLIC STATIC FUNCTION getInstance()
        IF instance is null then
            instance = new Singleton()
        END IF
        RETURN instance
    END FUNCTION
END CLASS
BEGIN CLASS Client
    BEGIN PROCEDURE UseSingleton()
        FIELD instance = Singleton.getInstance()
    END PROCEDURE
END CLASS
The source code for the Singleton design pattern in various programming languages can be viewed and downloaded on the Project Repository – Github.

Additional Information

I have discovered some additional information about Singleton design pattern. If you have any additional information about Singleton design pattern that you'd like to share, please feel free to leave a comment.

Initialization Types

In the Singleton design pattern, the choice of initialization strategy plays a crucial role in determining when and how the instance is created. Here are the initialization types of the Singleton design pattern:

  1. Eager Initialization
    In this type of initialization, the Singleton instance is created as soon as the class is loaded into memory. This approach ensures that the instance is readily available whenever needed, which can be beneficial in applications where immediate access to the instance is required, or when the overhead of delayed instantiation is not acceptable.

  2. Lazy Initialization
    In this type of initialization, the Singleton instance is created only when it is first accessed. This approach ensures that the instance is instantiated only when it truly needed, which can be beneficial to reduce resource usage.

Singleton Design Pattern VS Static Class

Both Singleton design pattern and static classes provide similar functionality by ensuring that only a single instance can be created throughout the application's lifecycle. Due to these similarities, choosing between them can be challenging. Here are some key factors to consider before making a decision:

  • A Singleton can only create one instance throughout the application lifecycle, whereas a static class cannot create any instances at all.

  • A Singleton can have both static and non-static members, while a static class can only contain static members.

  • A Singleton can maintain state through instance variables, while a static class can only maintain state through static fields.

  • A Singleton can from another class or implement interfaces, while a static class cannot inherit from any class or implement interfaces.

Further Discoveries

Here are some further discoveries I have gathered from various sources that may provide a deeper understanding of Singleton design pattern:

  • The Singleton design pattern can be combined with other design patterns, such as Abstract Factory, Builder, Facade, or Prototype.

  • When implementing the Singleton design pattern in a multithreaded environment, it’s important to consider thread safety. Techniques such as double-checked locking and using static constructors can help ensure that the Singleton instance remains thread-safe.

  • Some programming languages offer built-in classes or mechanisms for implementing lazy initialization. For example, in C#, the Lazy<T> class can be used to achieve lazy initialization.

  • Using dependency injection frameworks can provide a more flexible way to manage dependencies compared to traditional Singleton implementations.

Reference

  1. Singleton Design Pattern – Sourcemaking

  2. Singleton Design Pattern – Refactoring.guru

Design Patterns

Part 4 of 4

In this series, I’ll share insights about design patterns. From foundational concepts to advanced applications, discover how these patterns enhance code organization, improve efficiency, and elevate your software development projects.

Start from the beginning

Facade Design Pattern

Introduction Hello all, today I back with another Design Patterns topic, and today I will share what i learned about Facade design pattern. I hope with this article you will know more about Facade design pattern and use it on your project. What It Is...