#include <iostream>
#include <string>
#include <map>
using namespace std;
class Singleton
{
public:
static void Register(string pName, Singleton* pItem);
static Singleton* Instance(string pName);
protected:
Singleton(){}
virtual ~Singleton(){}
private:
static map<string, Singleton* > m_Map;
};
map<string, Singleton* > Singleton::m_Map;
void Singleton::Register(string pName, Singleton* pItem)
{
m_Map.insert(make_pair(pName,pItem));
}
Singleton* Singleton::Instance(string pName)
{
Singleton* pItem = NULL;
map<string, Singleton* >::const_iterator iter = m_Map.begin();
while ( (iter!= m_Map.end()) && ( (*iter).first != pName) )
{
iter++;
}
if (iter != m_Map.end())
{
pItem = (*iter).second;
}
return pItem;
}
template<class Type>
class ConSingleton :public Singleton
{
public:
ConSingleton(string pName)
{
Register(pName, this);
m_strName = pName;
};
virtual ~ConSingleton(){};
void prt()
{
cout << m_strName <<endl;
}
private:
string m_strName;
};
int main()
{
ConSingleton<int>* pConSingleton = new ConSingleton<int>("wang");
ConSingleton<int>* p = (ConSingleton<int>*) Singleton::Instance("wang");
p->prt();
return 0;
}