Search⌘ K

Singleton Pattern Implementation

Explore how to implement the singleton design pattern in both C++ and Python. Understand the key principles that ensure only one instance of a class is created and how this is enforced through private constructors, static instance methods, and deleted copy operations. Gain practical skills by examining multiple implementations including the classical approach, Meyers’ singleton, and a Python example.

Example one: simple implementation

Here’s an example of the singleton pattern implementation in C++.

C++
#include <iostream>
class MySingleton{
private:
static MySingleton* instance;
MySingleton()= default;
~MySingleton()= default;
public:
MySingleton(const MySingleton&)= delete;
MySingleton& operator=(const MySingleton&)= delete;
static MySingleton* getInstance(){
if ( !instance ){
instance= new MySingleton();
}
return instance;
}
};
MySingleton* MySingleton::instance= nullptr;
int main(){
std::cout << '\n';
std::cout << "MySingleton::getInstance(): "<< MySingleton::getInstance() << '\n';
std::cout << "MySingleton::getInstance(): "<< MySingleton::getInstance() << '\n';
std::cout << '\n';
}

Code explanation

  • Line 3: We created the MySingleton class.

  • Lines 5–8: We declared a private static MySingleton, which will store the object of the class alongside a private constructor and destructor.

  • Lines 11–12: We deleted the copy constructor and assignment operator so that our instance can’t be copied. ...