單例模式
單例模式:建立一個須要使用的對象。這裏先分析爲何要用類來建立,原本能夠建立一個non-local靜態對象。就是在main函數以前建立 T a();這個對象。可是非局部靜態對象通常由「模版隱式具體化」造成,在多個編譯單元內,它的初始化順序未知(effective c++ 4th)。因此用class方法的形式來構建一個單例模式。c++
首先單例模式分爲餓漢式和懶漢式。
餓漢:很餓,很着急,須要儘早的構建對象。對象式提早構建好的。
懶漢:很懶,不着急,當對象須要用的時候,才構建對象。函數
1.餓漢式。spa
1 class Singleton{ 2 private: 3 Singleton(){} 4 Singleton(const Singleton & ); 5 Singleton& operator=(const Singleton& ); 6 static Singleton* ptr; 7 public: 8 Singleton* GetSingleton(){ 9 return ptr; 10 } 11 void deleteSingleton(){ 12 if(ptr!=nullptr){ 13 delete ptr; 14 ptr=nullptr; 15 } 16 } 17 }; 18 Singleton* Singleton::ptr=new Singleton();
2.懶漢式code
1 /* 2 class Uncopyable 3 protected: 4 Uncopyable() {} 5 ~Uncopyable() {} 6 private: 7 Uncopyable(const Uncopyable&); 8 Uncopyable& operator=(const Uncopyable&); 9 */ 10 //lazy man 11 class Singleton : private Uncopyable{ 12 private: 13 Singleton() {pthread_mutex_init(mutex);} 14 static Singleton* ptr; 15 static pthread_mutex_t mutex; 16 17 public: 18 Singleton* GetSingleton(){ 19 if(ptr==nullptr){ 20 mutex.lock() 21 if(ptr==nullptr){ 22 static Singleton single; 23 return &single; 24 } 25 mutex.unlock(); 26 } 27 return ptr; 28 } 29 }; 30 Singleton* Singleton::ptr=nullptr;