hello forum,
i am very new to c++; but not new to oop. i am a java programmer by profession. teaching myself c++ as my latest "hobby project".
please, can anybody tell me:
what is the c++ idiom for implementing a _real_ Singleton (as in, the GoF design pattern)?
by "real", i mean so that there is no way whatsoever to create more than one instance of the Singleton. if you're thinking, "double-checked locking", etc. please stop there. that's not what i'm getting at.
i'm talking about your basic, simple, canonical Singleton; simply for tutorial purposes. specifically, i want to implement a Singleton that will prevent a client from doing something like this:
1 2 3 4 5 6 7 8
|
...
Singleton* singleton = Singleton::getInstance();
singleton->doSummut();
// this shouldn't be allowed
Singleton* doubleton;
doubleton->doSummutElse();
...
|
with the implementation i've coded (see below), it is possible to create more than one instance (even with a private constructor). keep in mind: i am a novice with c++; please, be gentle ;¬)
thanks in advance for your help.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
#include <stdlib.h>
#include "Singleton.h"
using namespace std;
void useSingleton(){
Singleton* singleton = Singleton::getInstance();
singleton->doSummut();
// this shouldn't be allowed
Singleton* doubleton;
doubleton->doSummutElse();
}
//
//
//
int main(int argc, char** argv) {
useSingleton();
return (EXIT_SUCCESS);
}
|
================================
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
#ifndef _SINGLETON_H
#define _SINGLETON_H
#include <stdio.h>
#include <stdlib.h>
class Singleton{
public:
static Singleton* instance;
static Singleton* getInstance(){
if (instance == 0){
instance = new Singleton;
} // end if
return instance;
}
void doSummut(){
printf("Doing the deed in Singleton.doSummut()\n");
}
void doSummutElse(){
printf("Doing summut else in Singleton.doSummutElse()\n");
}
private:
Singleton();
};
Singleton* Singleton::instance = 0;
Singleton::Singleton(){
}
#endif /* _SINGLETON_H */
|