Trusted answers to developer questions

How to implement the singleton pattern

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

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. ​

svg viewer

Implementation

#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 instance
return 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;
}

RELATED TAGS

implement
singleton
design
pattern
object oriented
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?