Open In App

Singleton Pattern | C++ Design Patterns

A singleton pattern is a design pattern that ensures that only one instance of a class can exist in the entire program. This means that if you try to create another instance of the class, it will return the same instance that was created earlier.

The Singleton pattern is useful when we need to have only one instance of a class, for example, a single database connection shared by multiple objects as creating a separate database connection for every object may be costly.



Implementation of the Singleton Pattern In C++

The Singleton pattern is a creational design pattern in C++ that ensures a class has only one instance and provides a global point of access to that instance. It is used when you want to control the instantiation of a class to ensure that there’s a single instance throughout the lifetime of your application.



Below is an example implementation of the Singleton pattern in C++:




#include <iostream>
 
class Singleton {
public:
    // Static method to access the singleton instance
    static Singleton& getInstance()
    {
        // If the instance doesn't exist, create it
        if (!instance) {
            instance = new Singleton();
        }
        return *instance;
    }
 
    // Public method to perform some operation
    void someOperation()
    {
        std::cout
            << "Singleton is performing some operation."
            << std::endl;
    }
 
    // Delete the copy constructor and assignment operator
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;
 
private:
    // Private constructor to prevent external instantiation
    Singleton()
    {
        std::cout << "Singleton instance created."
                  << std::endl;
    }
 
    // Private destructor to prevent external deletion
    ~Singleton()
    {
        std::cout << "Singleton instance destroyed."
                  << std::endl;
    }
 
    // Private static instance variable
    static Singleton* instance;
};
 
// Initialize the static instance variable to nullptr
Singleton* Singleton::instance = nullptr;
 
int main()
{
    // Access the Singleton instance
    Singleton& singleton = Singleton::getInstance();
 
    // Use the Singleton instance
    singleton.someOperation();
 
    // Attempting to create another instance will not work
    // Singleton anotherInstance; // This line would not
    // compile
 
    return 0;
}

Output
Singleton instance created.
Singleton is performing some operation.






Below is the explanation of the above code:

When you run this program, you’ll see that only one instance of the Singleton is created, and attempting to create another instance is prevented. The Singleton instance is accessed through the getInstance method, making it globally accessible within your codebase.

Diagram explaining the Singleton Pattern in C++

The Singleton pattern is a creational design pattern that ensures a class has only one instance and provides a global point of access to that instance.

Key Components:

  1. Singleton Class: This is the class that you want to make a singleton. It has a private constructor, private destructor, and a private static member variable to hold the single instance of the class.
  2. Static Member Variable: This is a private static member variable within the Singleton class that holds the single instance of the class. It is usually initialized to nullptr or an instance of the class itself.
  3. Static Method (getInstance): A public static method within the Singleton class called getInstance. This method is responsible for creating the instance if it doesn’t exist or returning the existing instance if it does. It ensures that there’s only one instance of the class.
  4. Delete Copy Constructor and Assignment Operator: To prevent copying of the Singleton instance, the copy constructor and assignment operator should be deleted within the Singleton class.

FLOW DIAGRAM OF SINGLETON PATTERN IN C++

Above diagram of singleton pattern works as follows:

  1. Initialization: The static member variable in the Singleton class is initialized to nullptr (or an instance of the class) when the program starts.
  2. First Access (Lazy Initialization): When the getInstance method is called for the first time, it checks if the static member variable is nullptr. If it is, it creates a new instance of the Singleton class using its private constructor. If it’s not nullptr, it returns the existing instance.
  3. Subsequent Accesses: For all subsequent calls to getInstance, the method simply returns the existing instance created during the first access.
  4. Usage: Clients access the Singleton instance by calling getInstance() and can then use the methods and data members of the Singleton as needed.

In the diagram above, Singleton is the Singleton class, instance is the static member variable holding the single instance, and getInstance() is the static method responsible for managing access to that instance.

Advantages of the Singleton Pattern in C++ Design Patterns

Here are the advantages of the Singleton pattern in C++:

Disadvantages of the Singleton Pattern in C++ Design Patterns

Here are some of the disadvantages of using the Singleton pattern in C++:

Uses of the Singleton Pattern

Here are some common use cases for the Singleton pattern in C++:

These are just a few examples of how the Singleton pattern can be applied to manage and control resources, state, and functionality in various types of applications. It provides a convenient way to ensure a single point of access and management for such scenarios.


Article Tags :