8.9. Creating a Singleton Class
Problem
You have a class that must only ever be instantiated once, and you need to provide a way for clients to access that class in such a way that the same, single object is returned each time. This is commonly referred to as a singleton pattern, or a singleton class.
Solution
Create a static member that is a pointer to the
current class, restrict the use of constructors to create the class by making them
private, and provide a public static member function that clients can use to access the
single, static instance. Example 8-9
demonstrates how to do this.
Example 8-9. Creating a singleton class
#include <iostream>
using namespace std;
class Singleton {
public:
// This is how clients can access the single instance
static Singleton* getInstance();
void setValue(int val) {value_ = val;}
int getValue() {return(value_);}
protected:
int value_;
private:
static Singleton* inst_; // The one, single instance
Singleton() : value_(0) {} // private constructor
Singleton(const Singleton&);
Singleton& operator=(const Singleton&);
};
// Define the static Singleton pointer
Singleton* Singleton::inst_ = NULL;
Singleton* Singleton::getInstance() {
if (inst_ == NULL) {
inst_ = new Singleton();
}
return(inst_);
}
int main() {
Singleton* p1 = Singleton::getInstance();
p1->setValue(10);
Singleton* p2 = Singleton::getInstance();
cout << "Value = " << p2->getValue() << '\n';
}Discussion
There are many situations where you want at most one instance of a class—this is why ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access