单例模式
学习这三人的:
C++单例模式_微学苑(编程第一站) http://www.weixueyuan.net/view/1292.html
C++设计模式——单例模式 | 果冻想 http://www.jellythink.com/archives/82
他讲了在单例模式中线程安全
设计模式C++实现(4)——单例模式 - wuzhekai的专栏 - 博客频道 - CSDN.NET http://blog.csdn.net/wuzhekai1985/article/details/6665869
他主要讲了单例模式与工厂模式的结合。
我自己的领悟:
1、单例模式应该就像一个全局变量,为了方便在全局中使用。单例模式不能被实例化,全局中只能有唯一的变量。
要注意应该把设计成单例模式的这个类的构造函数以及复制构造函数设计成私有的或者保护的,以防止在其他地方值被修改。
在多线程中,可能出现多次初始的事情,解决办法:1、利用Java中的双检锁机制 2、利用静态初始化,在主函数前先初始化(可能与编译器有关)
在实际生产过程中,没必要每调用一次就析构一次,因此可以这个类中以私有的方式(防止被调用)定义另一个类,这个类的成员函数是个析构函数,可以在这个函数中析构所有要想释放的资源,最后把这个类定义为静态变量。这样在程序结束时,程序会自动析构全局变量和静态变量,然后自动调用这个静态类中的析构函数。
2、单例模式一般经常和工厂模式一起使用。
自己代码:
1 #include <iostream> 2 using namespace std; 3 4 class Singleton 5 { 6 public: 7 static Singleton* GetInstance() 8 { 9 if(instance_ == NULL) 10 { 11 instance_ = new Singleton(); 12 } 13 return instance_; 14 } 15 /* 16 //the second method(非线程安全) 17 static Singleton& GetInstance() 18 { 19 static Singleton instance; 20 21 return instance; 22 } 23 24 Singleton& s1 = Singleton::GetInstance(); 25 Singleton& s2 = Singleton::GetInstance(); 26 */ 27 ~Singleton() 28 { 29 cout<<" ~Singleton()..."<<endl; 30 } 31 class Garbo 32 { 33 public: 34 ~Garbo() 35 { 36 if(Singleton::instance_ != NULL) 37 { 38 delete instance_; 39 } 40 } 41 }; 42 private: 43 Singleton& operator = (const Singleton& other); 44 Singleton(const Singleton & other); 45 Singleton() 46 { 47 cout<<"Singleton..."<<endl; 48 } 49 static Singleton* instance_; 50 51 static Garbo garbo_; 52 }; 53 Singleton * Singleton::instance_; 54 Singleton::Garbo Singleton::garbo_; 55 56 int main() 57 { 58 Singleton *a1 = Singleton::GetInstance(); 59 Singleton *a2 = Singleton::GetInstance(); 60 61 // Singleton a3 (*a1); 拷贝构造函数 62 63 64 return 0; 65 }