模板实现单例模式单例模式有多种写法,下⾯⽤模板类以三种⽅式实现单例模式。
1.懒汉模式
#include <iostream>
#include <stdio.h>
#include <pthread.h>
//懒汉模式
template <typename T>
class Singleston
{
public:
static T* GetInstance(){
if(NULL == instance_)
{
pthread_mutex_lock(&g_mutex);
单例模式的几种实现方式if(NULL == instance_)
{
instance_ = new T;
}
pthread_mutex_unlock(&g_mutex);
}
return instance_;
}
private:
static T * volatile instance_;
static pthread_mutex_t g_mutex;
};
template <typename T>
T* volatile Singleston<T>::instance_ = NULL;
template <typename T>
pthread_mutex_t Singleston<T>::g_mutex = PTHREAD_MUTEX_INITIALIZER;
2.饿汉模式
//饿汉模式
template <typename T>
class Singleston
{
public:
static T* GetInstance(){
return instance_;
}
private:
static T * volatile instance_;
};
template <typename T>
T* volatile Singleston<T>::instance_ = new T;
3.静态模式
//静态模式
template <typename T> class Singleton{
public :
static T* GetInstance(){ static T instance;
return &instance;
}
private:
Singleton();
~Singleton();
};
验证:
#include <singleston.h>
#include <pthread.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
class ApplicationImpl
{
public:
ApplicationImpl()
{
qDebug() << "ApplicationImpl ..." << endl;
}
~ApplicationImpl()
{
qDebug() << "~ApplicationImpl ..." << endl;
}
void Run()
{
qDebug() << "Run ..." << endl;
}
};
typedef Singleton < ApplicationImpl > Application;
void *routine(void *arg)
{
Application::GetInstance().Run();
}
int main(int argc, char *argv[])
{
Application::GetInstance().Run();
pthread_t tid;
int ret;
if ((ret = pthread_create(&tid, NULL, routine, NULL)) != 0) {
fprintf(stderr, "pthread create: %s\n", strerror(ret));
exit(EXIT_FAILURE);
}
Application::GetInstance().Run();
pthread_join(tid, NULL);
return 0;
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论