//static 实现单例模式
#include <iostream>
#include <cstdlib>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
class Singleton
{
private:
static Singleton* cInstance;
Singleton()
{
}
public:
static Singleton* GetInstance()
{
if(cInstance == NULL)//只会new一次
{
cout<<"new Singleton()"<<endl;
cInstance = new Singleton();
}
return cInstance;
}
void print()
{
cout<<"I'm Singleton!'"<<endl;
}
};
Singleton* Singleton::cInstance = NULL;
void func()
{
Singleton * s = Singleton::GetInstance();
Singleton * s1 = Singleton::GetInstance();
Singleton * s2 = Singleton::GetInstance();
cout<<s<<" "<<s1<<" "<<s2<<endl; //输出为:
//new Singleton
//0x372f58 0x372f58 0x372f58
//I'm Singleton!'
//I'm Singleton!'
//I'm Singleton!'
//new Singleton() 只调用了一次,而且s s1 s2三个的地址一模一样,都指向同一个对象
s->print();
s1->print();
s2->print();
}
int main(int argc, char** argv) {
func();
return 0;
}
C++学习笔记16 static 实现单例模式
最新推荐文章于 2024-01-21 18:36:04 发布