The singleton design pattern is used to restrict a class to only one instance at a time. This restriction is achieved by changing the accessibility of the constructor to private
so that a new instance cannot be created using that constructor from outside the class. The static method getInstance()
(defined in the class) creates a new instance after checking if an instance already exists. If it does, the same instance is returned; otherwise, a new instance is created and returned. The static variable instance
keeps track of the existing instance of the class.
In Python, the constructor is used to create instances; you do not need to use the getInstance()
method. However, an additional method __new__()
is used along with the __init__()
method to create and initialize an instance, respectively.
#include <iostream>using namespace std;class Singleton{private:static Singleton* instance;Singleton(){cout << "New instance created!" << endl;}public:static Singleton* getInstance(){// Check if an instance already exists:if(instance == nullptr)instance = new Singleton(); // Create a new instancereturn instance;}};Singleton* Singleton::instance = nullptr;int main(){// Private default constructor can't be accessed:// Singleton* s = new Singleton();Singleton* s = Singleton::getInstance();Singleton* t = Singleton::getInstance();// Print address of where 's' and 't' point// to make sure that it is the same object:cout << "'s' points to: " << s << endl<< "'t' points to: " << t << endl;return 0;}