首页 > 其他 > 详细

设计模式3——单例模式

时间:2014-09-16 12:24:10      阅读:177      评论:0      收藏:0      [点我收藏+]

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

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

 

具体实例:

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 tow instances is the same!" << endl;
39     }
40     else{
41         cout << "The tow instances is different!" << endl;
42     }
43     SingleInstance::release();
44 }
45 
46 #endif

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

设计模式3——单例模式

原文:http://www.cnblogs.com/MiniHouse/p/3974586.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!