注册表式单例模式详解java_C++单例模式之注册表方法 | 学步园

#include

#include

#include

using namespace std;

class Singleton1{

private:

static map mapList;

static Singleton1* _instance;

public:

static Singleton1* GetInstance(string name){

_instance = LookUp(name);

return _instance;

}

static void Register(string name, Singleton1* single){

Singleton1* regist = LookUp(name);

if (regist != NULL){

return;

}else{

mapList.insert(make_pair(name, single));

}

}

protected:

static Singleton1* LookUp(string name){

map::iterator iter = mapList.find(name);

if (iter != mapList.end())

return iter->second;

else

return NULL;

}

};

Singleton1* Singleton1::_instance = NULL;

map Singleton1::mapList;

class MySingleton : public Singleton1{

private:

MySingleton(){

}

public:

static void Regist(){

Singleton1::Register("MySingleton",new MySingleton());

}

void Print(){

cout << "this is MySingleton" << endl;

}

};

class MySingleton1 : public Singleton1{

private:

MySingleton1(){}

public:

static void Regist(){

Singleton1::Register("MySingleton1",new MySingleton1());

}

void Print(){

cout << "this is MySingleton1" << endl;

}

};

static void before_main()

{

cout << "before main" << endl;

MySingleton::Regist();

MySingleton1::Regist();

}

static void before_main() __attribute__((constructor));

int main()

{

cout << "--Singleton1--" << endl;

Singleton1* obj1 = MySingleton::GetInstance("MySingleton");

Singleton1* obj2 = MySingleton::GetInstance("MySingleton");

cout << obj1 << endl;

cout << obj2 << endl;

MySingleton* my1 = (MySingleton*)obj1;

MySingleton* my2 = (MySingleton*)obj2;

my1->Print();

my2->Print();

Singleton1* ob1 = MySingleton::GetInstance("MySingleton1");

Singleton1* ob2 = MySingleton::GetInstance("MySingleton1");

cout << ob1 << endl;

cout << ob2 << endl;

MySingleton1* my11 = (MySingleton1*)ob1;

MySingleton1* my12 = (MySingleton1*)ob2;

my11->Print();

my12->Print();

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值