单例模式
一、概念
单例模式是一种常用的软件设计模式。它的核心结构只包含一个被称为单例的特殊类。它的目的是保证一个类仅有一个实例,并提供一个访问它的全局访问点,该实例被所有程序模块共享
二、类型
懒汉式、饿汉式和双重锁的形式。
懒汉:第一次用到类的实例的时候才回去实例化。
饿汉:单例类定义的时候就进行实例化。
三、代码
#include <iostream> #include <mutex> #include <thread> using namespace std; mutex mu;//线程互斥对象
/*饿汉*/ class Singleton_Hungry { private: Singleton_Hungry() { cout << "我是饿汉式,在程序加载时,我就已经存在了。" << endl; } static Singleton_Hungry* singleton; public: static Singleton_Hungry* getInstace() { return singleton; } }; //静态属性类外初始化 Singleton_Hungry* Singleton_Hungry::singleton = new Singleton_Hungry;
/*懒汉*/ class Singleton_Lazy { private: Singleton_Lazy() { cout << "我是懒汉式,在别人需要我的时候,我才现身。" << endl; } static Singleton_Lazy* singleton; public: static Singleton_Lazy* getInstance() { if (NULL == singleton) { mu.lock();//关闭锁 if (NULL == singleton) { singleton = new Singleton_Lazy; } mu.unlock();//打开锁 } return singleton; } }; Singleton_Lazy* Singleton_Lazy::singleton = NULL;
四、简单写法
不定义单例属性,通过static全局属性的功能,直接在函数里返回
static Singleton *instance() { static Singleton *instance = new Singleton(); return instance; }
或
static Singleton &instance() { static Signaleton instance; return instance; }
五、模板+静态变量
#ifndef SINGLETON_H #define SINGLETON_H template <typename T> class Singleton { public: static T* instance(); }; template <typename T> T* Singleton<T>::instance() { static T p; return &p; } #endif // SINGLETON_H
参考:http://www.qtbig.com/page/15/
长风破浪会有时,直挂云帆济沧海!
可通过下方链接找到博主
https://www.cnblogs.com/judes/p/10875138.html