C++实现单例模式的简单例程
来源:互联网 发布:淘宝怎样做充值话费 编辑:程序博客网 时间:2024/06/13 22:07
在Java中使用单例模式是常用的事情
这里使用C++实现一次单例模式,虽然实际场景中很少使用
这次例程有四个文件
Singleton.h
Singleton.cpp
Demo.cpp
Client.cpp
#ifndef _SINGLETON_H_#define _SINGLETON_H_#include <iostream>using namespace std;#include <pthread.h> static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;class Singleton{ public: static Singleton *GetInstance(){ cout<<"to get Singleton instance"<<endl; if (m_Instance == NULL){ pthread_mutex_lock(&mutex); //lock(); if (m_Instance == NULL){ m_Instance = new Singleton(); } pthread_mutex_unlock(&mutex); //unlock(); } return m_Instance; } private: Singleton(){ cout<<"Singleton construction"<<endl; } static Singleton *m_Instance ; // This is important ---- Garbage Collector class GC { public: GC(){ cout<<"GC construction"<<endl; } ~GC(){ cout<<"GC destruction"<<endl; // We can destory all the resouce here if (m_Instance != NULL){ delete m_Instance; m_Instance = NULL; cout<<"Singleton destruction"<<endl; } } }; // 定义一个静态成员,在程序结束时,系统会调用它的析构函数 static GC gc; //垃圾回收类的静态成员 public : void SayHello();};#endif
Singleton.cpp #include <stdio.h>#include "Singleton.h"Singleton *Singleton::m_Instance = NULL;Singleton::GC Singleton::gc;//static int index;void Singleton::SayHello(){ static int index; printf("###%s(%d)###index=%d\n", __FUNCTION__, __LINE__,index++);}
Demo.cpp #include <stdio.h>#include "Singleton.h"int printDemo(){ //Singleton *singletonObj = Singleton::GetInstance(); Singleton *singletonObj = Singleton::GetInstance(); printf("(%s:%d)singletonObj=%p\n", __FUNCTION__, __LINE__, singletonObj); singletonObj->SayHello(); return 0;}
Client.cpp #include <stdio.h>#include "Singleton.h"int printDemo(); // or put to a header fileint main(int argc, char *argv[]) { Singleton *singletonObj = Singleton::GetInstance(); printDemo(); printf("(%s:%d)\n", __FUNCTION__, __LINE__); singletonObj->SayHello(); return 0;}
运行结果 $ g++ Client.cpp Demo.cpp Singleton.cpp$ ./a.out GC constructionto get Singleton instanceSingleton constructionto get Singleton instance(printDemo:8)singletonObj=0x190a010###SayHello(10)###index=0(main:9)###SayHello(10)###index=1GC destructionSingleton destruction
阅读全文
0 0
- C++实现单例模式的简单例程
- 【C++】单例模式的一种简单实现的模板
- 单例模式的简单代码实现
- C++单例模式的简单实现
- 单例模式的简单有用实现
- 单例模式的C++简单实现
- 单例模式的简单实现
- 单例模式的C++简单实现
- PHP单例模式例程
- 【Objective-C】单例模式的实现
- Objective-C 单例模式的实现
- c++--Singleton单例模式的实现
- 单例程序的实现
- 单例模式简单实现
- (C++)设计模式------单例模式 singleton(简单的实现和对象释放的控制) -- 创建型模式
- 单例设计模式(C#) 简单模式
- Objective-C 【简单的单例模式引入】
- 单例模式的简单使用(QML调用C++)
- MySQL内连接、外链接
- php 配置信息,502的错误信息
- windows虚拟环境
- mysql数据库主从同步
- 关于部分android手机连拍模式,手机拍照上传的图片旋转了90度的c#解决方案
- C++实现单例模式的简单例程
- google浏览器 屏蔽 Slow network is detected. Fallback font will be used while loading
- 打印平行四边形
- Mybatis一级和二级缓存正确解答
- 数据库索引的实现原理
- 码云git
- Node.js的全局对象和全局变量
- 有关CGI、FastCGI和PHP-fpm的简述
- github 建静态博客