单例模式(Singleton)
单例模式保证一个类只有一个实例,并提供一个访问它的全局访问点。
类负责保存它自身的唯一实例,这个类可以保证没有其他实例被创建,并且可以提供一个访问该实例的方法。
类的实例化需要构造函数,构造函数可以被调用,是因为一般的构造函数是公有的。通过显式地把构造函数设置为私有的或保护的,可以使类外部无法实例化。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 //Singleton.h 2 3 #ifndef _SINGLETON_H_ 4 #define _SINGLETON_H_ 5 6 class Singleton //单例类 7 { 8 public: 9 static Singleton* GetInstance(); //静态成员函数,用于获取唯一的实例 10 protected: 11 Singleton(); 12 private: 13 static Singleton* instance; //私有成员,唯一的实例 14 }; 15 16 #endif
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 //Singleton.cpp 2 3 #include "Singleton.h" 4 #include <iostream> 5 using namespace std; 6 7 Singleton* Singleton::instance = NULL; 8 9 Singleton::Singleton() 10 { 11 cout << "Singleton..." << endl; 12 } 13 14 Singleton* Singleton::GetInstance() 15 { 16 if (instance == NULL) 17 { 18 instance = new Singleton(); 19 } 20 cout << "Get instance..." << endl; 21 return instance; 22 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 //main.cpp 2 3 #include "Singleton.h" 4 #include <iostream> 5 using namespace std; 6 7 int main(int argc, char* argv[]) 8 { 9 Singleton* singleton1 = Singleton::GetInstance(); 10 Singleton* singleton2 = Singleton::GetInstance(); 11 return 0; 12 }
通过单例模式可以限制客户对唯一实例的访问。