常用设计模式之单例模式

单例模式:用来创建独一无二的,只能够有一个实例的对象。
单例模式的应用场景:有一些对象其实只需要一个,比如:线程池,缓存,对话框,处理偏好设置和注册表的对象,日志对象,充当打印机,显卡等设备的驱动程序对象。这些对象只能够拥有一个实例,如果创建出了多个实例,就会导致一些程序的问题。程序的行为异常,资源使用的过量,或者导致不一致的结果。常用来管理共享的资源,比如数据库的连接或者线程池。

Singleton经典结构为:
Singleton经典结构
我们通过维护一个static的成员来记录这个唯一的对象实例。通过提供一个static的接口instance来获得这个唯一的实例。

//Singleton.h
#ifndef _SINGLETON_H_
#define _SINGLETON_H_

#include <iostream>
using namespace std;

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

//Singleton不可以被实例化,因此我们将其构造函数声明为protected,或者private。
protected:
    Singleton();

private:
    static Singleton* _instance;
};

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

Singleton *Singleton::_instance = 0;

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

Singleton *Singleton::Instance()
{
    if (0==_instance)
    {
        _instance = new Singleton();
    }
    return _instance;
}
//Main.cpp
#include "Singleton.h"
#include <iostream>
using namespace std;

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

    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/fan_xingwang/article/details/73555649