Singleton模式

  Singleton模式解决问题十分常见,我们怎样去创建一个唯一的变量(对象)?在基于对象的设计中我们可以通过创建一个全局变量(对象)来实现,在面向对象和面向过程结合的设计范式(如C++中)中,我们也还是可以通过一个全局变量实现这一点。但是当我们遇到了纯粹的面向对象范式中,这一点可能就只能是通过Singleton模式来实现了

Singleton.h

 1 #ifndef _SINGLETON_H_
 2 #define _SINGLETON_H_
 3 
 4 #include <iostream>
 5 
 6 using namespace std;
 7 
 8 class Singleton
 9 {
10 public:
11     static Singleton *Instance();
12 
13 protected:
14     Singleton();
15 private:
16     static Singleton *_instance;
17 };
18 
19 #endif // !_SINGLETON_H_

Singleton.cpp

 1 #include <iostream>
 2 #include "Singleton.h"
 3 
 4 using namespace std;
 5 
 6 Singleton *Singleton::_instance=0;
 7 
 8 Singleton::Singleton()
 9 {
10     cout << "Singleton..." << endl; 
11 }
12 
13 Singleton* Singleton::Instance() 
14 { 
15     if (_instance == 0) 
16     {
17         _instance = new Singleton();
18     }
19     return _instance; 
20 }

main.cpp

#include "Singleton.h"
#include <iostream> 
using namespace std; 
int main(int argc,char* argv[]) 
{
    Singleton* sgn = Singleton::Instance();
    return 0;
}

代码说明
  Singleton模式的实现无须补充解释,需要说明的是,Singleton不可以被实例化,因此我们将其构造函数声明为protected或者直接声明为private。 

 

原文地址:https://www.cnblogs.com/Malphite/p/10985123.html