单键模式

#include <mutex>
#include <iostream>
using namespace std;

class Single{
public:
    static Single*  ShareInstance();
    static void ReleaseInstance();

private:
    Single();
    ~Single();
    Single(const Single &other);
    Single& operator=(const Single &other);
    
private:
    static Single *m_pObj;
    static mutex *m_pMutex;
};



#include "Single.h"
Single* Single::m_pObj = NULL;
mutex* Single::m_pMutex = new mutex();
Single* Single::ShareInstance(){
    if (NULL == m_pObj) {
        m_pMutex->lock();
        m_pObj = new Single();
        m_pMutex->unlock();
    }
    return m_pObj;
}

void Single::ReleaseInstance(){
    if (m_pObj) {
        delete m_pObj;
        m_pObj = NULL;
    }
}

Single::Single(){
    
}
Single::~Single(){
    
}

 

EX:

#include <iostream>
class SingleEx{
public:
    static SingleEx& ShareInstance();
private:
    SingleEx();
    ~SingleEx();
    SingleEx(const SingleEx &other);
    SingleEx& operator =(const SingleEx &other);
 
};

#include "SingleEx.h"


SingleEx& SingleEx::ShareInstance(){
    static SingleEx obj;
    return obj;
}

SingleEx::SingleEx(){
    
}

SingleEx::~SingleEx(){
    
}

 

posted @ 2014-07-10 17:27  酱酱爱  阅读(247)  评论(0编辑  收藏  举报