单例模式
意图:一个类只能有一个实例,提供一个全局访问点
适用场景:一个类频繁的创建与销毁,又想节省资源
关键:构造函数定义为private,删除拷贝构造函数和赋值构造函数
template<typename T>
class Singleton {
public:
//返回实例
static T& instance() {
//保证init()只执行一次
pthread_once(&ponce_, &_single_inheritance::init);
return *value;
}
//删除拷贝构造函数和赋值构造函数
Singleton(const const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
private:
Singleton();
~Singleton();
static void init() {
value_ = new T();
}
private:
static pthread_once_t ponce_;
static T* value_;
};
template<typename T>
pthread_once_t Singleton<T>::ponce_ = PTHREAD_INCE_INIT;
template<typename T>
T* Singleton<T>::value_= NULL;