//Singleton.h
#include <map>
#include <iostream>
#include <string>
using namespace std;
class Singleton;
class Singleton
{
public:
static void Register(const char* name, Singleton*);
static Singleton* Instance();
virtual void f1(){ cout << "Sigleton f1" << endl; }
virtual ~Singleton();
protected:
static Singleton* Lookup( const char* name );
private:
static Singleton * _instance;
static map<string, Singleton*> _register;
};
class MySingleton : public Singleton
{
public:
MySingleton()
{
}
void f1(){ cout << "MySingleton f1" << endl; }
};
//Singleton.cpp
#include "Singleton.h"
Singleton * Singleton::_instance = 0;
map<string, Singleton*> Singleton::_register;
void Singleton::Register(const char* name, Singleton* ps)
{
char envname[255] = "SINGLETON=";
strcat( envname, name );
if( _putenv( envname) == 0 )
_register.insert( make_pair( string(name), ps ) );
}
Singleton* Singleton::Instance()
{
if(_instance == 0)
{
const char* singletonName = getenv("SINGLETON");
_instance = Lookup(singletonName);
}
return _instance;
}
Singleton* Singleton::Lookup( const char* name )
{
if(_register.count(string(name)) == 0)
return NULL;
map<string, Singleton*>::iterator iter = _register.find(string(name));
if( iter != _register.end() )
return (*iter).second;
else
return NULL;
}
Singleton::~Singleton()
{
}
定义一个静态对象:
static MySingleton theMySingleton;
为了保证theMySingleton的可用性,在main()来进行注册
Singleton::Register("MySingleton", &theMySingleton);
Singleton::Instance()->f1();
输出:
MySingleton f1