在C++编程语言中,单例模式应用的例子如下述代码所示(这里仅仅提供一个示例;由于加入了锁,这代码是线程安全的):
1 // ... 2 3 class lock 4 { 5 public: 6 lock(); 7 lock(lock const & l); 8 ~lock(); 9 lock & operator =(lock const & l); 10 void request(); 11 void release(); 12 // ... 13 }; 14 15 lock::lock() 16 { 17 // ... 18 } 19 20 // ... 21 22 lock::~lock() 23 { 24 // ... 25 } 26 27 // ... 28 29 void lock::request() 30 { 31 // ... 32 } 33 34 void lock::release() 35 { 36 // ... 37 } 38 39 // ... 40 41 // assumes _DATA_TYPE_ has a default constructor 42 template<typename _DATA_TYPE_> 43 class singleton 44 { 45 public: 46 static _DATA_TYPE_ * request(); 47 static void release(); 48 49 private: 50 singleton(); 51 singleton(singleton<_DATA_TYPE_> const & s); 52 ~singleton(); 53 singleton<_DATA_TYPE_> & operator =(singleton<_DATA_TYPE_> const & s); 54 static _DATA_TYPE_ * pointer; 55 static lock mutex; 56 // ... 57 }; 58 59 template<typename _DATA_TYPE_> 60 _DATA_TYPE_ * singleton<_DATA_TYPE_>::pointer = nullptr; 61 62 template<typename _DATA_TYPE_> 63 lock singleton<_DATA_TYPE_>::mutex; 64 65 template<typename _DATA_TYPE_> 66 _DATA_TYPE_ * singleton<_DATA_TYPE_>::request() 67 { 68 if(singleton<_DATA_TYPE_>::pointer == nullptr) 69 { 70 singleton<_DATA_TYPE_>::mutex.request(); 71 72 if(singleton<_DATA_TYPE_>::pointer == nullptr) 73 { 74 singleton<_DATA_TYPE_>::pointer = new _DATA_TYPE_; 75 } 76 77 singleton<_DATA_TYPE_>::mutex.release(); 78 } 79 80 return singleton<_DATA_TYPE_>::pointer; 81 } 82 83 template<typename _DATA_TYPE_> 84 void singleton<_DATA_TYPE_>::release() 85 { 86 if(singleton<_DATA_TYPE_>::pointer != nullptr) 87 { 88 singleton<_DATA_TYPE_>::mutex.request(); 89 90 if(singleton<_DATA_TYPE_>::pointer != nullptr) 91 { 92 delete singleton<_DATA_TYPE_>::pointer; 93 94 singleton<_DATA_TYPE_>::pointer = nullptr; 95 } 96 97 singleton<_DATA_TYPE_>::mutex.release(); 98 } 99 } 100 101 template<typename _DATA_TYPE_> 102 singleton<_DATA_TYPE_>::singleton() 103 { 104 // ... 105 } 106 107 // ... 108 109 int main() 110 { 111 int * s; 112 113 s = singleton<int>::request(); 114 115 // ... 116 117 singleton<int>::release(); 118 119 return 0; 120 }