设计模式3——单例模式

单例模式是一个比较简单的设计模式,只产生一个具体的对象,一般用于全局变量,保证整个系统所使用的变量是唯一的。

单例模式中,一般将构造函数和析构函数都设置为私有的,获取和释放时采用静态函数实现。

具体实例:

SingleInstance.h内容

 1 #ifndef SingleInstance_H_H
 2 #define SingleInstance_H_H
 3 
 4 #include <iostream>
 5 using namespace std;
 6 
 7 class SingleInstance
 8 {
 9 public:
10     static SingleInstance* getInstance(){
11         if(instance == NULL){
12             instance = new SingleInstance();
13         }
14         return instance;
15     }
16 
17     static void release(){
18         if(instance != NULL){
19             delete instance;
20             instance = NULL;
21         }
22     }
23 
24 private:
25     SingleInstance() {}
26     ~SingleInstance() {}
27     static SingleInstance *instance;
28 };
29 
30 SingleInstance* SingleInstance::instance = NULL;
31 
32 
33 void SingleInstanceTest()
34 {
35     SingleInstance *instance1 = SingleInstance::getInstance();
36     SingleInstance *instance2 = SingleInstance::getInstance();
37     if(instance1 == instance2){
38         cout << "The two instances is the same!" << endl;
39     }
40     else{
41         cout << "The two instances is different!" << endl;
42     }
43     SingleInstance::release();
44 }
45 
46 #endif

 由于创建的对象是同一个,因此release()函数调用一次即可。

原文地址:https://www.cnblogs.com/MiniHouse/p/3974586.html