1. 程式人生 > >c++設計模式之單例模式

c++設計模式之單例模式

() ati 之前 class urn 測試 main -- cpp

單例模式:
目的:保證每個類只有一個靜態對象
實現方式:
1.構造函數私有化
2.公有靜態類對象指針
3.產生靜態類對象指針的公有函數
分類:
懶漢式:在需要的時候才進行初始化
優點:避免內存消耗
缺點:需要加鎖,影響執行效率
餓漢式:一開始就進行初始化
優點:不需要加鎖,執行速度快
缺點:會造成內存消耗

註意:
1.雙檢索機制--->懶漢式,在判斷之前需要在加上一個鎖
2.資源//singleton.h

  1 #pragma once
  2 #include <mutex>
  3 
  4 
  5 class singleton
  6 {
  7 public:
  8     static
singleton* singleton_; 9 static singleton* getInstance(); 10 void doSomeThing(); 11 private: 12 static std::mutex mutex_; 13 singleton(); 14 ~singleton(); 15 }; 16 17 18 //singleton.cpp----此為懶漢式 19 #include "pch.h" 20 #include <iostream> 21 #include "singleton.h
" 22 23 singleton *singleton::singleton_ = NULL; 24 std::mutex singleton::mutex_; 25 26 singleton::singleton() 27 { 28 } 29 30 31 singleton::~singleton() 32 { 33 if (singleton_) 34 { 35 delete singleton_; 36 singleton_ = NULL; 37 } 38 } 39 40 singleton* singleton::getInstance()
41 { 42 if (singleton_==NULL) 43 { 44 std::lock_guard<std::mutex> lock(mutex_); 45 if (singleton_==NULL) 46 { 47 singleton_ = new singleton(); 48 } 49 } 50 return singleton_; 51 } 52 53 void singleton::doSomeThing() 54 { 55 std::cout << "do some thing!"; 56 } 57 58 //singleton.cpp----此為惡漢式 59 #include "pch.h" 60 #include <iostream> 61 #include "singleton.h" 62 63 singleton *singleton::singleton_ = new singleton();; 64 std::mutex singleton::mutex_; 65 66 singleton::singleton() 67 { 68 } 69 70 71 singleton::~singleton() 72 { 73 if (singleton_) 74 { 75 delete singleton_; 76 singleton_ = NULL; 77 } 78 } 79 80 singleton* singleton::getInstance() 81 { 82 return singleton_; 83 } 84 85 void singleton::doSomeThing() 86 { 87 std::cout << "do some thing!"; 88 } 89 90 91 //測試代碼 92 #include "pch.h" 93 #include <iostream> 94 #include "singleton.h" 95 96 int main() 97 { 98 singleton::getInstance()->doSomeThing(); 99 getchar(); 100 }

運行結果:

do some thing!

c++設計模式之單例模式