from:http://www.haogongju.net/art/1535572
作者:mr_nop | 出处:博客园 | 2012/7/10 11:44:40
最近看的android代码,看到一个模板实现的单例模式,相当易用。
直接继承即可。做个记录
1 template <typename TYPE>
2 class Singleton
3 {
4 public:
5 static TYPE& getInstance() {
6 Mutex::Autolock _l(sLock);
7 TYPE* instance = sInstance;
8 if (instance == 0) {
9 instance = new TYPE();
10 sInstance = instance;
11 }
12 return *instance;
13 }
14 protected:
15 ~Singleton() { };
16 Singleton() { };
17 private:
18 Singleton(const Singleton&);
19 Singleton& operator = (const Singleton&);
20 static Mutex sLock;
21 static TYPE* sInstance;
22 };
23 //用法如下。class OverlayMgr : public Singleton<OverlayMgr>
24 {
25 }