Singleton 模式

个人认为 Singleton 模式是设计模式中最为简单、最为常见、最容易实现,也是最应该
熟悉和掌握的模式。且不说公司企业在招聘的时候为了考察员工对设计的了解和把握,考的
最多的就是 Singleton 模式。

 1 ///////Singleton.h/////////////////////
 2 #ifndef _SINGLETON_H_
 3 #define _SINGLETON_H_
 4 
 5 class Singleton
 6 {
 7 public:
 8     static Singleton* Instance();
 9 protected:
10     
11 private:
12     Singleton();//不可被实例化,因此把构造函数声明为私有
13     static Singleton* _instance;
14 };
15 #endif
 1 ///////////////////Singleton.cpp////////////////
 2 #include "Singleton.h"
 3 #include <iostream>
 4 using namespace std;
 5 
 6 Singleton* Singleton::_instance = 0 ;
 7 Singleton::Singleton()
 8 {
 9     cout<<"instance"<<endl;
10 }
11 
12 Singleton* Singleton::Instance()
13 {
14     if (_instance == 0)
15     {
16         _instance = new Singleton();
17     }
18 
19     return _instance ;
20 }
 1 #include "Singleton.h"
 2 #include <iostream>
 3 using namespace std;
 4 
 5 int main()
 6 {
 7     Singleton* sgn1 = Singleton::Instance();
 8     Singleton* sgn2 = Singleton::Instance();//第二次实例化时返回的是原指针
 9     
10     getchar();
11     return 0;
12 }
原文地址:https://www.cnblogs.com/csxcode/p/3691595.html