How to Create Singleton Class in C++
A singleton class is a design pattern in C++ that limits a class's instantiation to a single instance and offers a global point of access to the code. It assures that the class is used only once through the program execution. The singleton pattern is regularly used while a single control point is required, including when coping with a shared aid or configuration settings. A singleton's primary objective is to provide a single point of manipulation over a resource or capability, along with a configuration manager, a logger, a database connection, or any other circumstance where many instances could cause trouble.
Implementation of Singleton Class in C++
Step-1:
Create a singleton class header file. This file will define the class, its private constructor, and other members that might be required.
Example:
class One
{
private:
One();
static One* instance;
public:
static One* getInstance();
// Remaining Code
};
Step-2:
Construct a .C++ file to implement the singleton class methods.
Example:
#include "One.h"
One* One::instance = nullptr;
One::One()
{
// Private constructor code
}
One* One::getInstance()
{
if (instance == nullptr)
{
instance = new One();
}
return instance;
}
Step-3:
The singleton class can now be used in other parts of your code.
Example:
#include "One.h"
int main()
{
One* obj1 = One::getInstance();
One* obj2 = One::getInstance();
return 0;
}
Step-4:
Include all the .Cpp files in your compilation command to collect your code.
Features of Singleton Class in C++
Private Constructor: The singleton class design pattern relies primarily on the private constructor in a singleton class. It assures that a singleton class can only be produced within the class, preventing external code from immediately instantiating more than once. The private constructor reduces instance creation to the singleton class, giving you control access to the single instance.
- Making the constructor private prevents different instructions from using the new operator to create singleton instances.
- Because the constructor is private, the singleton class can manage how and when the single instance is created. It is frequently performed via a static member function (including getInstance()), which assures that simply one instance is produced and returned.
- The private constructor contains the creation mechanism within the singleton class, abstracting the details of instance creation from external code.
Note: While the private constructor assures that there is only one instance of the class, other factors of singleton implementation consist of thread safety in multithreaded situations and proper memory control handled efficiently.
Static Instance: In a singleton class, the static instance is a vital element that holds the single instance of the class that the singleton pattern ensures. It is a static member variable used to hold and maintain the program's single instance of the class. The static instance permits several parts of the code to access the same singleton class instance.
- In the singleton class, declare a static member variable. This variable will hold the class instance.
- To indicate that no instance has been generated, initialize the static instance to nullptr.
- Provide a static member method (generally known as getInstance()) assigned to make the instance if it no longer exists and return the present instance in any other case.
- An instance is created when the getInstance() technique is used for the first time. Subsequently, getInstance() operations return the already constructed instance.
Note: The static instance is an important element of the singleton pattern; it is also required to correctly handle its different functions, including the private constructor to prevent external instantiation, thread safety in multithreaded situations, and powerful memory management.
Static Access Method: A vital component of the C++ singleton design pattern is the static access function called getInstance() in singleton classes. It gives a restricted method of accessing the class in a single instance. This approach must be created if the example does not exist; otherwise, it must return to the current example. The static access method assures that one example of the instance is ever created and utilized by encapsulating the code for instance creation.
- Create a static member function in the singleton class with the usual name getInstance().
- Check if the static instance, frequently a static pointer, is nullptr within the getInstance() function. If it returns nullptr, the example still needs to be created.
- Use the class private constructor to make a new instance if the existing one is nullptr.
- Return the instance, whether it was just created or already there.
Applications of Singleton Class
Configuration File:
You can use a singleton configuration manager to store and manage application configuration settings, such as database connection strings, API keys, and different components that must be accessed globally. One common use of the singleton sample in C++ is the configuration file. Make sure that configuration settings are loaded and accessed in a controlled and uniform manner throughout the application and singleton classes are used for configuration management.
Logging:
To manage and control the logging behavior in various code regions, a singleton logger can centralize logging throughout an application. The creation of software should include logging. During an application's operation, it includes gathering relevant data about the state and behavior of the application. The logging process can be centralized and controlled in C++ using a singleton class, making it simpler to manage and maintain.
Hardware Interface Access:
Singleton classes can manage hardware resources in systems that interact with physical devices, such as controlling access to a single instance of a printer or scanner. It is possible to manage resources and communications with hardware devices by implementing a device manager in C++ using a singleton class. Device managers can assist in restricting access to hardware resources, managing device connections, and performing as a central hub for device-related tasks.
Caching:
The caching method may be implemented using singleton classes to increase the efficiency, which stores regularly used data or resources in memory. Performance can be stronger by implementing a caching method in C++ that uses a singleton class to store regularly used data in memory. Caching might be useful when computing or retrieving data is expensive and you want to avoid repeatedly doing that.
Initialization types in Singleton Class:
Classic Singleton Class:
It is the simplest technique for implementing a singleton class. When getInstance() is used for the first time, the instance is produced slowly. One of the most effective and well-known uses of the singleton design pattern in C++ is the Classic Singleton. It gives a means to guarantee that a class has just one instance and a point of getting access to that instance from anywhere. The Classic Singleton uses lazy initialization, which means that the instance is most effectively created while it is first required.
Early Initialization:
When discussing singleton classes, the term "early initialization" generally refers to building the singleton instance at program startup or some stage in initialization rather than doing it while it's first required. It can be helpful when you need to ensure that the singleton instance is accessible and eliminates any potential overhead due to Lazy Initialization.
Example:
#include <bits/stdc++.h>
using namespace std;
class One
{
private:
string tutorialandexample, website;
static One*
instancePtr;
One()
{
}
public:
static One* getInstance()
{
if (instancePtr == NULL)
{
instancePtr = new One();
return instancePtr;
}
else
{
return instancePtr;
}
}
void setValues(string tutorialandexample,string website)
{
this->tutorialandexample = tutorialandexample;
this->website = website;
}
void print()
{
cout << tutorialandexample << " Website is " <<
tutorialandexample << ".com" << endl;
}
};
One* One ::instancePtr = NULL;
int main()
{
One* example = One ::getInstance();
example->setValues("Ramesh","tutorialandexample");
example ->print();
cout << endl;
One* example1 = One ::getInstance();
example1->setValues("Suresh","tutorialandexample");
example1->print();
return 0;
}
Output:
![How to Create Singleton Class in C++](https://static.tutorialandexample.com/cpp/how-to-create-singleton-class-in-cpp1.png)
- The main() function starts.
- One* example = One::getInstance(); creates the singleton instance.
- One* example1 = One::getInstance(); retrieves the same singleton instance.
- example->print(); calls the print() member function of the singleton instance.
- The main() function returns, and the program exits.
Alternatives for Singleton Class in C++:
- Dependency Injection
- Monostate Pattern
- Session Context
Dependency Injection:
You can manually pass instances of objects to the areas of your program that require them rather than employing a Singleton Class. It makes testing easier and better managed. Frameworks for dependency injection may provide and control these dependencies. A Dependency Injection (DI) design pattern allows for creating dependencies in a category instead of the class having to create or control them. This design pattern encourages loose coupling and facilitates testing, upgradability, and maintenance. Despite being different patterns, Singleton and Dependency Injection may be combined to handle dependencies inside of a Singleton Class.
Monostate Pattern:
The Monostate Pattern typically called the "Shared State" pattern, is a variation of the Singleton pattern that puts more value on distributing state among many instances than on guaranteeing a single instance. The Monostate Pattern makes all instances of a class act as though they're the same instance by having them all share the same internal state. Members with access to shared data can help with this.
Session Context:
In the context of a Singleton magnificence, the term "Session Context" usually denotes managing and maintaining a set of data or settings that are particular to a session or user. It could be preserving information for a session or saving user-specific options and settings, which is commonly important in software programs like applications and client-server systems.