CSingleton
CSingleton是一个模板类,用于实现单例的创建,单例模式参考:单例模式
CSingleton的实现
CSingleton是为了让所有类都可以简单的实现单例,所以考虑使用友元类的模板方法来实现,所有需要实现单例的对象,将CSingleton添加为友元类,就可以直接使用友元的方法:
1 2 3 4 5 6 7 8 9 10 11 12 13
| template <typename T> class Csingleton { public: template <typename... Args> static T* getInstance(Args&&... args) { static T instance(std::forward<Args>(args)...);
return &instance; } private: };
|
使用实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| #include <string> #include <typeinfo> #include <iostream>
template <typename T> class Csingleton { public: template <typename... Args> static T* getInstance(Args&&... args) { static T instance(std::forward<Args>(args)...);
return &instance; }
private: };
class test { private: test() { std::cout << "init test" << std::endl; } public: ~test(){ } friend Csingleton<test>; static test *getInstance(){ return Csingleton<test>::getInstance(); } };
int main() { std::cout << "test start" << std::endl; test *p1 = test::getInstance(); test *p2 = test::getInstance(); std::cout << "test end" << std::endl; return 0; }
|
只运行了一次构造函数,并且是在需要的时候才创建