Chinaunix首页 | 论坛 | 博客
  • 博客访问: 16523
  • 博文数量: 9
  • 博客积分: 370
  • 博客等级: 一等列兵
  • 技术积分: 85
  • 用 户 组: 普通用户
  • 注册时间: 2008-12-10 00:42
文章分类
文章存档

2011年(1)

2010年(5)

2008年(3)

我的朋友
最近访客

分类: C/C++

2008-12-11 00:21:36

利用模板实现单例模式,这样我们就可以对任意类型创建单例模式
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) |
0

上一篇:没有了

下一篇:Unix Daemon Server Programming

给主人留下些什么吧!~~