利用模板实现单例模式,这样我们就可以对任意类型创建单例模式
singleton.h
#ifndef SINGLETON_H #define SINGLETON_H #include <pthread.h>
template< class T > class Singleton { class InstanceHolder { public: InstanceHolder() : mObject(0) {} ~InstanceHolder() { delete mObject; } T* get() { return mObject; } void set(T* p) { delete mObject; mObject = p; }
private: InstanceHolder(const InstanceHolder&); InstanceHolder& operator=(const InstanceHolder&);
private: T* mObject; }; public: static T* instance() { if (!mFlag) { pthread_mutex_lock(&mMutex); if (!mFlag) { mInstance.set(new T()); mFlag = 1; } pthread_mutex_unlock(&mMutex); } return mInstance.get(); }
private: static InstanceHolder mInstance; static volatile int mFlag; static pthread_mutex_t mMutex;
Singleton(); Singleton(const Singleton&);
Singleton& operator=(const Singleton&); };
template<class T> typename Singleton<T>::InstanceHolder Singleton<T>::mInstance ; template<class T> volatile int Singleton<T>::mFlag = 0; template<class T> pthread_mutex_t Singleton<T>::mMutex = PTHREAD_MUTEX_INITIALIZER;
#endif
|
下面我们利用这个模板来创建我们所需要的单例类型
app.h
#ifndef APP_H #define APP_H #include "singleton.h" #include <iostream>
using namespace std ;
class ServiceListener{ public: ServiceListener(){cout << "ServiceListener" << endl ;}; ~ServiceListener(){cout << "~ServiceListener" << endl ;}; }; class ServiceController : public ServiceListener { public: ServiceController(){cout << "ServiceController" << endl;} ~ServiceController(){cout << "~ServiceController" << endl;}
int init(){cout << "init" << endl ;}; int run(){cout << "run" << endl ;}; int start(){cout << "start" << endl ;}; int stop(){cout << "stop" << endl ;}; };
typedef Singleton<ServiceController> ServiceControl;
#endi
|
app.cc
#include "app.h" #include "singleton.h"
int main() { ServiceController *ctl = ServiceControl::instance() ; ctl->init() ; ctl->run() ; ctl->start() ; ctl->stop() ; return 0 ;
|
阅读(625) | 评论(0) | 转发(0) |