相关概念参考:【C++】C++ 单例模式总结(5种单例实现方法)_单例模式c++实现-CSDN博客
#include<iostream>
class LazySingle{
public:
static LazySingle& getInstance(){
static LazySingle instance;
return instance;
}
void hello(){
std::cout<<"Congratulations"<<std::endl;
}
private:
LazySingle(){};
};
class LazySinglePtr{
public:
static LazySinglePtr* getInstance(){
static LazySinglePtr instance;
return &instance;
}
void hello(){
std::cout<<"Congratulations"<<std::endl;
}
private:
LazySinglePtr(){};
};
class HungrySingle{
public:
static HungrySingle& getInstance(){
return instance_;
}
private:
static HungrySingle instance_;
HungrySingle(){};
};
HungrySingle HungrySingle::instance_;
int main(){
std::cout<<"懒汉引用模式:"<<std::endl;
auto& lazy1=LazySingle::getInstance();
LazySingle& lazy2=LazySingle::getInstance();
std::cout<<" lzay1="<<&lazy1<<" lzay2="<<&lazy2<<" instance="<<&LazySingle::getInstance()<<std::endl;
lazy1.hello();
std::cout<<"懒汉指针模式:"<<std::endl;
auto lazyptr1=LazySinglePtr::getInstance();
LazySinglePtr* lazyptr2=LazySinglePtr::getInstance();
std::cout<<" lzay1="<<lazyptr1<<" lzay2="<<lazyptr2<<" instance="<<LazySinglePtr::getInstance()<<std::endl;
lazyptr1->hello();
std::cout<<"饿汉模式:"<<std::endl;
HungrySingle& hungry1=HungrySingle::getInstance();
HungrySingle& hungry2=HungrySingle::getInstance();
std::cout<<" hungry1="<<&hungry1<<" hungry2="<<&hungry2<<" instance="<<&HungrySingle::getInstance()<<std::endl;
return 0;
}
输出:
懒汉引用模式:
lzay1=0x7ff61a279e90 lzay2=0x7ff61a279e90 instance=0x7ff61a279e90
Congratulations
懒汉指针模式:
lzay1=0x7ff61a279ee0 lzay2=0x7ff61a279ee0 instance=0x7ff61a279ee0
Congratulations
饿汉模式:
hungry1=0x7ff61a2aa030 hungry2=0x7ff61a2aa030 instance=0x7ff61a2aa030