c++ 单例模式

#ifndef CCriticalSection_hpp
#define CCriticalSection_hpp

#include 
#include 
class CCriticalSection {
private:
    pthread_mutex_t mutex;
public:
    CCriticalSection();
    ~CCriticalSection();
public:
    void Lock();
    void Unlock();
};
#endif /* CCriticalSection_hpp */

#include "CCriticalSection.hpp"

CCriticalSection::CCriticalSection()
{
    pthread_mutex_init(&mutex,NULL);
}
CCriticalSection::~CCriticalSection()
{
    pthread_mutex_destroy(&mutex);
}
void CCriticalSection::Lock()
{
    pthread_mutex_lock(&mutex);
}
void CCriticalSection::Unlock()
{
    pthread_mutex_unlock(&mutex);
}

#include 
#include "CCriticalSection.hpp"
class Lock {
public:
    Lock(CCriticalSection vs):cs(vs) {
        cs.Lock();
    };
private:
    CCriticalSection cs;
};
#endif /* Lock_hpp */

#ifndef Game_hpp
#define Game_hpp

#include 
#include 
#include "CCriticalSection.hpp"
using namespace std;
class Game {
private:
    Game() {value=1;};
    Game(const Game&);
    Game& operator = (const Game&);
    static Game* myGame;
    static CCriticalSection cs;
public:
    int value;
    void sayHello();
    static Game* getInstance();
};
#endif /* Game_hpp */

#include "Game.hpp"
#include "Lock.hpp"
Game* Game::myGame = nullptr;
CCriticalSection Game::cs = *new CCriticalSection();
Game* Game::getInstance() {
    if (myGame ==nullptr) {
        Lock Lock(cs);
        if (myGame == nullptr) {
            myGame = new Game();
        }
    }
    return myGame;
}

void Game::sayHello() {
    printf("hello 单例,%d \n",value);
    value ++;
}

#include 
#include "Game.hpp"
int main(int argc, const char * argv[]) {
    // insert code here...
    std::cout << "Hello, 单例模式!\n";
    Game::getInstance()->sayHello();
    Game *game1 = Game::getInstance();
    game1->sayHello();
    Game *game = game1;
    game->sayHello();
    return 0;
}

你可能感兴趣的:(c++学习)