C++模式学习------单例模式

单例(Singleton)模式,是一种常用的软件设计模式。在应用这个模式时,单例对象的类必须保证只有一个实例存在。许多时候整个系统只需要拥有一个的全局对象,这样有利于我们协调系统整体的行为。例如一些类是属于工具,配置,日志性质的,程序很多的地方会用到,若每次都去new会增加了开销,也不好管理。这时候我们只需要一个实例对象就可以。这里是可以采用全局或者静态变量的方式,不过全局量没有封装,可能会有误用影响其他地方的情况。

Lazy Singleton 

 1 class Singleton  
 2 {  
 3      public:  
 4         static Singleton& Instance() 
 5                   //使用的时候初始化单例
 6         {  
 7             if(instance == NULL)                       
 8                 instance = new Singleton;  
 9              return *instance;                          
10         }  
11   
12      private: //为实现单例,需要将构造,复制构造都设为私有
13          Singleton();                                  
14          ~Singleton();  
15          Singleton(const Singleton&);  
16          Singleton& operator=(const Singleton&);  
17    
18          static Singleton* instance;  
19 };  

【这种模式不是线程安全的。多线程运行的时候,构造会出现问题。在这种情况下,需要加上互斥锁,来实现线程安全】

 1 class Singleton  
 2 {  
 3     public:  
 4         static Singleton& Instance() 
 5         {  
 6             if(instance== NULL)  //若未初始化则上锁初始化
 7             {     
 8                 Lock();//上锁  
 9                 if(instance== NULL)   
10                     instance= new Singleton;  
11                 Unlock();//解锁  
12             }  
13             return *instance;   
14         }     
15   
16     private:  //为实现单例需要将构造函数,复制构造函数设为私有
17         Singleton();   
18         ~Singleton();  
19         Singleton(const Singleton&);  
20         Singleton& operator=(const Singleton&);  
21   
22         static Singleton* instance;  
23 };  

Eager Singleton

 1 class Singleton  
 2 {  
 3     public:  
 4         static Singleton& Instance() 
 5                   //用的时候返回单例
 6         {  
 7             return instance;  
 8         }  
 9   
10     private:  //为实现单例,需要将构造,复制构造都设为私有
11         Singleton(); 
12         ~Singleton();  
13         Singleton(const Singleton&);  
14         Singleton& operator=(const Singleton&);  
15   
16         static Singleton instance;  //构造的时候初始化
17 };  

【初始化的时候构造完成,因此是线程安全的】

Meyers Singleton

 1 class Singleton  
 2 {  
 3     public:  
 4         static Singleton& Instance()  
 5                            //第一次使用的时候构造
 6         {  
 7             static Singleton instance;  
 8             return instance;  
 9         }  
10   
11     private:  
12         Singleton();  //  为实现单例,需要将构造复制构造设为私有
13         ~Singleton();  
14         Singleton(const Singleton&);  
15         Singleton& operator=(const Singleton&);       
16 };  

【在c++11之后这种模式是线程安全的】

原文地址:https://www.cnblogs.com/tyche116/p/8666224.html