您的位置:首页 > 其它

设计模式 -- 单例模式(Singleton)

2015-11-13 10:45 477 查看

单例模式

Singleton模式解决问题十分常见而且比较简单。那么什么是单例模式呢?其实就是创建一个唯一的类对象,内存中只占有一份。那么问题来了,要怎么创建一个唯一对象呢?当然,直接定义一个全局的对象可以实现,但在有些纯粹的面向对象语言中,如C#,jave中,就不能定义全局变量了。那么,除了全局变量还有什么是唯一性的呢?恩,没错,就是static静态变量。我们的单例模式就是通过一个静态的类成员函数实现的(创建对象)。

单例模式类对象是一个共享对象,内存中只有一份,节约了内存。它常常和工厂模式一起使用,因为工厂对象只需唯一一个就够了。

结构示意图:(一个static方法 + 一个对象指针)



示例代码

#ifndef __DesignMode__Singleton__
#define __DesignMode__Singleton__

#include <iostream>
using namespace std;

class Singleton
{
public:
static Singleton * Instance();

protected:
Singleton();

private:
static Singleton* _instance;
};

#endif /* defined(__DesignMode__Singleton__) */


#include "Singleton.h"
#include <iostream>
using namespace std;

Singleton* Singleton::_instance = 0;

Singleton::Singleton()
{
cout << "Singleton create ..." << endl;
}

Singleton* Singleton::Instance()
{
if (_instance == 0)
{
_instance = new Singleton();
}

return _instance;
}


#include "Singleton.h"
#include <iostream>
using namespace std;

int main(int argc,char* argv[])
{
Singleton* sgn1 = Singleton::Instance();
Singleton* sgn2 = Singleton::Instance();
Singleton* sgn3 = Singleton::Instance();

return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: