C++实现单例模式

来源:互联网 发布:s7总决赛数据统计 编辑:程序博客网 时间:2024/05/04 04:47


本文参考1:mafuli007

/*单例模式:确保一个类只有一个实例,并提供一个全局访问方式说明:在一个系统中要求一个类只有一个实例时才应当使用单例模式。反过来,如果一个类可以有几个实例共存,就需要对单例模式进行改进,使之成为多例模式(控制实例的数据,并提供全局的访问方式)。注释:下面的方式不支持多线程操作,要支持多线程需要再GetInstance方式内加上锁机制Created by Phoenix_FuliMa*/#include <iostream>using namespace std;class Singleton{private:static Singleton *instance;Singleton() {}Singleton(const Singleton& other);//拷贝构造函数和赋值构造函数最好也都声明为私有的Singleton & operator = (const Singleton &other);~Singleton(){}public:static Singleton* GetInstance(){if(instance == NULL){instance = new Singleton();}return instance;}void Show(){cout<<"i am the only one"<<endl;}};Singleton* Singleton::instance = NULL;int main(){Singleton *obj1 = Singleton::GetInstance();obj1->Show();Singleton *obj2 = Singleton::GetInstance();obj2->Show();system("pause");return 0;}


0 0