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++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- 一个简单的asp数据库操作类
- C#实现用于操作wav声音文件的类实例
- C#类的多态性详解
- 修复mysql数据库
- 在线管理数据库 类
- Lua中调用C++函数示例
- Lua面向对象之类和继承浅析
- Lua中类的实现原理探讨(Lua中实现类的方法)
- Lua教程(一):在C++中嵌入Lua脚本
- Lua中的类编程代码实例
- Lua教程(二):C++和Lua相互传递数据示例
- C#常用目录文件操作类实例
- c# 类和成员的修饰详细介绍
- C#中实现判断某个类是否实现了某个接口
- C#类的创建与初始化实例解析
- C#基础语法:结构和类区别详解