Singleton单例模式

来源:互联网 发布:网络安全生产会议内容 编辑:程序博客网 时间:2024/05/18 09:06

Singleton单例模式

Singleton 是对全局变量的取代策略
作用:保证一个类只能有一个实例,并提供一个全局唯一的访问点。

仅有一个实例:通过类的静态成员变量来体现。
提供访问它的全局访问点:访问静态成员变量的静态成员函数来体现。

《设计模式》一书中给出了一种很不错的实现,定义一个单例类,使用类的私有静态指针变量指向类的唯一实例,并用一个公有的静态方法获取该实例。

单例模式通过类本身来管理其唯一实例,这种特性提供了解决问题的方法。唯一的实例是类的一个普通对象,但设计这个类时,让它只能创建一个实例并提供对此实例的全局访问。唯一实例类Singleton在静态成员函数中隐藏创建实例的操作。习惯上把这个成员函数叫做Instance(),它的返回值是唯一实例的指针。

单例类Singleton有以下特征:

它有一个指向唯一实例的静态指针,并且是私有的;

它有一个公有的函数,可以获取这个唯一的实例,并且在需要的时候创建该实例;

它的构造函数是私有的,这样就不能从别处创建该类的实例。

 

UML图:

在Singleton模式的结构图中可以看到,我们通过维护一个static的成员变量_instance来记录这个唯一的对象实例。通过提供一个staitc的接口Instance来获得这个唯一的实例。

代码如下:

Singleton.h

#ifndef UNISE_SINGLETON_H_#define UNISE_SINGLETON_H_#include <boost/noncopyable.hpp>#include <pthread.h>namespace unise {/// @brief Thread-safe, no-manual destroy Singleton templatetemplate<typename T>class Singleton : boost::noncopyable {public:    /// @brief Get the singleton instance    static T* get() {        pthread_once(&_p_once, &Singleton::_new);        return _instance;    }private:    Singleton();    ~Singleton();    /// @brief Construct the singleton instance    static void _new() {        _instance = new T();    }    /// @brief  Destruct the singleton instance    /// @note Only work with gcc    __attribute__((destructor)) static void _delete() {        typedef char T_must_be_complete[sizeof(T) == 0 ? -1 : 1];        (void) sizeof(T_must_be_complete);        delete _instance;    }    static pthread_once_t _p_once;      ///< Initialization once control    static T*             _instance;    ///< The singleton instance};template<typename T>pthread_once_t Singleton<T>::_p_once = PTHREAD_ONCE_INIT;template<typename T>T* Singleton<T>::_instance = NULL;}#endif


原创粉丝点击