Where to use it:
You can use it whenever you need only one instance of a class.
But like all things too much isn't good. It can be alot of work to change your code when you decide to have more then one instance of your class in a later stage of development.
So be sure you'll only need one instance.
Creation:
Make your constructor private.
You create a static method (preferably called: instance) and this method will call your private constructor.
this instance will keep a static member of your class and returns this member whenever it is called.
header file:
Code:
class mySingleton
{
private:
mySingleton(void);
int data_;
public:
static mySingleton* instance(void);
int data();
void data(int data);
}
cpp file:
Code:
mySingleton::mySingleton() : data_(0)
{}
mySingleton* mySingleton::instance()
{
static mySingleton inst;
return &inst;
}
int mySingleton::data()
{
return data_;
}
void mySingleton::data(int data)
{
data_= data;
}
Now you'll be able to use the getters and setters of data_ in every class/function and data() will always return the same value.
example
This is the code for a simple logging mechanism :
log.h
Code:
#include <string>
#include <fstream>
using namespace std;
class log
{
private:
log(void);
string filename_;
ofstream filestream_;
public:
~log(void);
static log* instance(void);
void initialize(string filename);
ofstream& debug_log();
};
cpp file
Code:
#include "log.h"
log::log(void) : filename_("")
{
}
log::~log(void)
{
}
log* log::instance(void)
{
static log instance;
return &instance;
}
void log::initialize(string filename)
{
filename_=filename;
filestream_.open(filename.c_str());
}
ofstream& log::debug_log()
{
return filestream_;
}
Now I only have to initialize the class once and I'll be able to write to the log file whenever I want without haveing a global variable or opening the logfile in every function/class.
Code:
#include "log.h"
void myfunction(void)
{
log::instance()->debug_log()<<"In function"<<endl;
}
int main()
{
log::instance()->initialize("mylog.txt");
log::instance()->debug_log()<<"Before function"<<endl;
myfunction();
log::instance()->debug_log()<<"After function"<<endl;
return 0;
}