您的位置:首页 > 编程语言 > C语言/C++

c++ 单例模式

2016-03-10 14:32 323 查看
#ifndef CCriticalSection_hpp
#define CCriticalSection_hpp

#include <stdio.h>
#include <pthread.h>
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 <stdio.h>
#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 <stdio.h>
#include <iostream>
#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 <iostream>
#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++