Code snippet below:
singleton.h
#include <iostream
class Singleton {
public:
Singleton() {
if (exists_already) {
std::cout << "You mustn't do that !" << std::endl;
// failure action !!!
}
else {
std::cout << "Singleton first init" << std::endl;
exists_already = true;
}
}
void singleAction() {
std::cout << "Run single action" << std::endl;
}
private:
static bool exists_already;
};
SingleFactory.h
#include <singleton.h>
class SingleFactory {
public:
static Singleton *getInstance() {
return &single;
}
private:
static Singleton single;
};
SingleFactory.cpp
(pay attention that it keeps movables belonging to Singleton class)
#include <singlefactory.h>and finally the usage example
Singleton SingleFactory::single;
bool Singleton::exists_already = false;
main.cpp
include <iostream>
#include <cstdlib>
#include <singlefactory.h>
using namespace std;
int main(int argc, char *argv[])
{
Singleton *n = SingleFactory::getInstance();
cout << "Hello, world!" << endl;
n->singleAction();
Singleton *nextS = new Singleton();
Singleton singleS;
return EXIT_SUCCESS;
}
Brak komentarzy:
Prześlij komentarz