Intent:
Ensure a class only has one instance and provide a global point of access to it.
Are usually implemented through static methods.
#include <memory>
#include <iostream>
using namespace std;
using std::auto_ptr;
class MySingle
{
public:
static MySingle* Instance();
void SayHello()
{
std::cout << "Hello World!" << std::endl;
}
~MySingle()
{
cout<< "destructor called" <<endl;
}
private:
MySingle() {};
static auto_ptr<MySingle> sm_inst;
};
auto_ptr<MySingle> MySingle::sm_inst;
MySingle* MySingle::Instance()
{
if(sm_inst.get() == 0)
{
sm_inst = auto_ptr<MySingle> (new MySingle);
}
return sm_inst.get();
}
int main()
{
MySingle* pSing = MySingle::Instance();
if(pSing != 0)
{
pSing->SayHello();
}
return 0;
}
When to use this pattern:
- Use the singleton pattern when:
- There must be exactly one instance of a class and it must be accessible to clients from a well known access point.
- You have a class whose objects are intended to be used as readonly.