Tuesday

Software Design Patterns: Singleton pattern using C++

Why?

Ensure a class only has one instance and provide a global point of access to it.

 

Code:

#include <iostream>
using namespace std;

class Singleton {
public:
static Singleton* getInstance();
protected:
Singleton();
private:
static Singleton* _instance;
};

Singleton* Singleton::_instance = 0;

Singleton::Singleton() {
cout << "Singleton::Singleton()" << endl;
}

Singleton* Singleton::getInstance() {
if (_instance == 0) {
_instance = new Singleton;
}
return _instance;
}

int main()
{
Singleton* singleton = Singleton::getInstance();
}


Sample run:

Singleton::Singleton()

No comments:

De-Enshittify Apps

Enshittification is the gradual, systematic decline in the quality of a product, service or digital platform caused by profit seeking, lock-...