在编写sylar服务器时,遇到一种没见过的非常好的单例模式实现,找遍CSDN就只有两篇博客,还没有讲解。只好自己尝试理解。
1、singleton.h头文件代码#ifndef __SINGLETON_H__ #define __SINGLETON_H__ template2、说明 模板类型参数class Singleton { public: static T* GetInstance() { static T v; return &v; } }; template class SingletonPtr { public: static std::shared_ptr GetInstance() { static std::shared_ptr v(new T); return v; } }; #endif
第一个要说明的点就是模板类型参数class X = void 和 int N = 0的作用。他们能使得 对于同一个类型T,产生多个实例,产生多个实例后,可以用这两个参数来索引这些实例。但这是和单例模式的思想冲突的。而且在整个sylar服务器框架中所有用到该模板的地方,也确实没有使用到这两个参数。
如果有大佬知道这两个参数的其他意义烦请在评论区留言,非常感谢。
这个只要请搞清楚静态局部变量的内存分配和初始化方式即可,参考下面我的另一篇博客。
C++中全局变量,静态变量,静态局部变量 的初始化和内存分配问题
这个单例模式的强大之处在于它具有很高的复用性,sylar服务器中也确实有很多需要用单例模式的类都使用了该模板。
4、一个简单的实验#include#include using namespace std; class X { public: void func() { cout << "XXXXXXXXXXX" << endl; } }; class Y { public: void func() { cout << " YYYYYYYYYY" << endl; } }; template // X:为了创造多个实例对应的 Tag class Singleton // N:同一个 Tag 创造多个实例索引 { public: static T* GetInstance() { static T v; static int x; x++; printf("x = %dtX: %pn", x, &x); return &v; } }; int main() { X* x1 = Singleton ::GetInstance(); x1->func(); X* x2 = Singleton ::GetInstance(); x2->func(); X* x11 = Singleton ::GetInstance(); x11->func(); printf("%pn%pn%pn", x1, x2, x11); return 0; }
输出:



