Intent
Ensure a class only has one instance, and provide a global point of access to it.
// DesignPatterns.cpp: 定义应用程序的入口点。
//
#include "DesignPatterns.h"
#include <list>
#include <utility>
using namespace std;
class Singleton {
public:
static Singleton* Instance() {
if (instance_ == nullptr)
return new Singleton();
return instance_;
}
virtual void SingletonOperation() {
std::cout << __FUNCTION__ << std::endl;
}
virtual void GetSingletonData() {
std::cout << __FUNCTION__ << std::endl;
// TODO. process singletonData
}
protected:
Singleton() {
}
static Singleton* instance_;
};
Singleton* Singleton::instance_ = 0;
class NameSingletonPair {
public:
NameSingletonPair() {
}
NameSingletonPair(const char* n, Singleton* s) :name_(n), singleton_(s) {
}
std::string name() const{
return std::string(name_);
}
Singleton* singleton() const{
return singleton_;
}
private:
const char* name_;
Singleton* singleton_;
};
class SingletonCollection : public Singleton{
public:
SingletonCollection() {
std::list<NameSingletonPair > li{};
registry_ = &li;
}
static void Register(const char* name, Singleton* s) {
std::cout << __FUNCTION__ << std::endl;
if (registry_ == nullptr)
return;
/* auto sinle = NameSingletonPair(name, s);
registry_->push_back(sinle);*/
}
static Singleton* Instance() {
std::cout << __FUNCTION__ << std::endl;
const char* singletonName = getenv("SINGLETON");
// user or envirnment supplies this at startup
auto instance_ = Lookup(singletonName);
// lookup returns 0 if there's no such singleton
return instance_;
}
protected:
static Singleton* Lookup(const char* name) {
std::cout << __FUNCTION__ << std::endl;
//for (auto item : (*registry_)) {
// if (std::string(item.name()).compare(std::string(name)) == 0)
// {
// return item.singleton();
// }
//}
return nullptr;
}
private:
static std::list<NameSingletonPair >* registry_;
};
class MySingleton : public Singleton {
public:
static Singleton* Instance() {
if (instance_ == 0) {
instance_ = new MySingleton();
}
return instance_;
}
virtual void SingletonOperation() {
std::cout << __FUNCTION__ << std::endl;
}
virtual void GetSingletonData() {
std::cout << __FUNCTION__ << std::endl;
// TODO. process singletonData
}
private:
MySingleton() {
SingletonCollection::Register("MySingleton", this);
}
private:
void* singletonData;
};
int main()
{
cout << "Hello CMake." << endl;
MySingleton::Instance()->SingletonOperation();
MySingleton::Instance()->GetSingletonData();
SingletonCollection::Instance();
return 0;
}