您的位置:首页 > 职场人生

面试题2:实现Singleton模式

2016-06-30 10:31 302 查看
书上给的是C#实现,自己写几个C++实现:

1. 基本版,适用于单线程

class Singleton
{
public:
static Singleton * Instance();
static void Destroy();
protected:
Singleton(){}
private:
static Singleton * m_pInstance;
};

Singleton * Singleton::m_pInstance = NULL;

Singleton * Singleton::Instance()
{
if (m_pInstance == NULL)
m_pInstance = new Singleton;
return m_pInstance;
}

void Singleton::Destroy()
{
delete m_pInstance;
}


2. 多线程,使用加锁机制

利用winAPI中的加锁

#include <Windows.h>

class Locker
{
protected:
friend class Singleton;
CRITICAL_SECTION cs;

public:
Locker(){
::InitializeCriticalSection(&cs);
}
void lock(){
::EnterCriticalSection(&cs);
}
void unlock(){
::LeaveCriticalSection(&cs);
}
~Locker(){
::DeleteCriticalSection(&cs);
}
};

class Singleton
{
public:
static Singleton * Instance();
static void Destroy();
protected:
Singleton(){}
private:
static Singleton * m_pInstance;
};

Singleton * Singleton::m_pInstance = NULL;

Singleton * Singleton::Instance()
{
Locker *lock = new Locker;
lock->lock();
if (m_pInstance == NULL)
m_pInstance = new Singleton;
lock->unlock();
return m_pInstance;
}

void Singleton::Destroy()
{
delete m_pInstance;
}


3. 模版实现

class Singleton
{
public:
static T * Instance();
static void Destroy();
protected:
Singleton(){}
private:
static T * m_pInstance;
};

template <typename T>
T * Singleton<T>::m_pInstance = NULL;

template <typename T>
T * Singleton<T>::Instance()
{
if (m_pInstance == NULL)
m_pInstance = new T;
return m_pInstance;
}

template <typename T>
void Singleton<T>::Destroy()
{
delete m_pInstance;
}


参考资料:
http://blog.csdn.net/a342374071/article/details/18270643/ http://www.cnblogs.com/liyuan989/p/4264889.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: