中国开发网: 论坛: Visual C: 贴子 83468
furnace
SingleTon design pattern implemented by C++ Template!
//=============================================================================
// singleton.hpp, Implementation of template Singleton design pattern
//
// author: furnace
//
// example with thread safe:
//
// class SingletonClass : public XSingleton<SingletonClass>,
// protected XLockableObject
// {
// friend class XSingleton<MyClass>;
// protected:
// SingletonClass();
// ...
// public:
// void lockedMethodWithMacro()
// {
// AUTO_LOCK_THISSCOPE // macro for lock whole mehtod,
// // or you can use AutoLock lockScope(this)
// // if u don't want to use macro
// ...
// }
// void lockedMethodWithoutmacro()
// {
// AutoLock lockScope(this);
// }
// };
//
// SingletonClass* pInstance = SingletonClass::getInstance();
// .....
// SingletonClass::release(); // don't forget to call this method!!
//
//=============================================================================

#ifndef SINGLETON_HPP
#define SINGLETON_HPP
//-----------------------------------------------------------------------------

#include <pthread.h>
//-----------------------------------------------------------------------------

/**
* AutoRun class that used for scope locked
*/
template <class T, void (T::*SF)(), void (T::*EF)() > class AutoRunstatic
{
public:
AutoRunstatic(T* p) : pInstance(p)
{
(pInstance->*SF)();
}

virtual ~AutoRunstatic()
{
(pInstance->*EF)();
}
private:
T* pInstance;
};
//-----------------------------------------------------------------------------

/**
* LockableObject
*/
class XLockableObject
{

public:
XLockableObject()
{
pthread_mutexattr_init(&m_attr);
pthread_mutex_init(&m_mutex, &m_attr);
}

virtual ~XLockableObject()
{
}

void lock()
{
pthread_mutex_lock(&m_mutex);
}

void unlock()
{
pthread_mutex_unlock(&m_mutex);
}

protected:
typedef AutoRunstatic <XLockableObject , &(XLockableObject::lock), &(XLockableObject::unlock)> AutoLock;
#define AUTO_LOCK_THISSCOPE AutoLock lockScope(this);

private:
pthread_mutex_t m_mutex;
pthread_mutexattr_t m_attr;
};
//-----------------------------------------------------------------------------

/**
* Singleton design pattern
*/
template <typename T> class XSingleton
{

protected:
// forbid Copy and asign
XSingleton() {}
XSingleton(const XSingleton& ) {}
XSingleton& operator=(const XSingleton&) {}

public:
virtual ~XSingleton() {}

/**
* Get the instance
*/
static T* getInstance()
{
if (!m_pInstance)
{
m_pInstance = new T;
}
return m_pInstance;
}

/**
* release
*/
static void release()
{
if (m_pInstance)
{
delete m_pInstance;
m_pInstance = NULL;
}
}

private:
static T* m_pInstance;

};

template <typename T> T* XSingleton<T>::m_pInstance = NULL;
//-----------------------------------------------------------------------------

#endif
I don't mind if you r FAT.
I don't mind if you r UGLY.
I don't mind if you ACT CUTE.
But I can't STAND if you r FAT, UGLY and still ACT CUTE.

相关信息:


欢迎光临本社区,您还没有登录,不能发贴子。请在 这里登录