设计模式-单例模式
来源:互联网 发布:咸宁软件开发 编辑:程序博客网 时间:2024/04/29 23:13
单例模式(Singleton):
保证一个类仅有一个实例,并提供一个访问它的全局访问点。
单例模式分为懒汉模式和饿汉模式,以及在创建实例的时候要考虑多线程问题,也就是需要上锁,上锁可以采用一般的锁,也可以采用双重锁的方式减少上锁时内核态与用户态切换导致的资源浪费,同时因为饿汉模式的特性,饿汉模式不涉及到多线程上锁问题。
接下来实现一下懒汉模式和饿汉模式,先不考虑多线程问题,最后在单独说下多线程问题的处理代码。
单例模式(懒汉)
.h
#pragma once#include <iostream>using namespace std;class CWork{private:static CWork * m_cWork;static int m_nMarkRunCount;CWork(){} //By using the constructor as a private block to prevent users from using the class variable.void DoWrite(){cout<<"WorkCount:"<<m_nMarkRunCount++<<endl;}public:static void GetInstance(){//Create a static function of the entityif(m_cWork == NULL){m_cWork = new CWork();}}static void WriteLog() {//work functionif(m_cWork == NULL){cout<<"no instance"<<endl;return ;}m_cWork->DoWrite();}};.cpp
#include "stdafx.h"#include "SingletonMode.h"CWork * CWork::m_cWork = NULL;int CWork::m_nMarkRunCount = 0;客户端调用:
#include "stdafx.h"#include "SingletonMode.h"#include <iostream>#include <string>using namespace std;int main(){CWork::WriteLog();CWork::GetInstance();CWork::WriteLog();CWork::WriteLog();return 0;}运行结果:
单例模式(饿汉)
.h
#pragma once#include <iostream>using namespace std;class CWork{private:static CWork * m_cWork;static int m_nMarkRunCount;CWork(){} //By using the constructor as a private block to prevent users from using the class variable.void DoWrite(){cout<<"WorkCount:"<<m_nMarkRunCount++<<endl;}public:static CWork* GetInstance(){//Create a static function of the entityif(m_cWork == NULL){m_cWork = new CWork();}return m_cWork;}static void WriteLog() {//work functionif(m_cWork == NULL){cout<<"no instance"<<endl;return ;}m_cWork->DoWrite();}};.cpp
#include "stdafx.h"#include "SingletonMode.h"CWork * CWork::m_cWork = CWork::GetInstance();int CWork::m_nMarkRunCount = 0;客户端调用:
#include "stdafx.h"#include "SingletonMode.h"#include <iostream>#include <string>using namespace std;int main(){CWork::WriteLog();CWork::WriteLog();CWork::WriteLog();return 0;}运行结果:
Static void GetInstance(){If(m_cWork == NULL){ Lock { If(m_cWork == NULL) { m_cWork = new CWork(); } } }}//注意第二个if的作用。
0 0
- 设计模式------单例模式
- 设计模式------单例模式
- 设计模式-单例模式
- 设计模式 - 单例模式
- 设计模式---单例模式
- 设计模式---单例模式
- 【设计模式】单例模式
- 设计模式-单例模式
- 设计模式----单例模式
- 设计模式--单例模式
- 设计模式-单例模式
- 设计模式-单例模式
- [设计模式] 单例模式
- 设计模式--单例模式
- 设计模式---单例模式
- 设计模式--单例模式
- 设计模式 -----单例模式
- 设计模式:单例模式
- qt5集成libcurl实现tftp和ftp的方法之三:搭建FTP时,当ftpServer端默认登录的目录不是根目录/时,有一个bug会产生的解决办法
- 身份验证中Cookies与 Tokens比较
- Lwip学习笔记之UDP
- CMUSphinx语音识别工具包的概述
- HDU 1018 Big Number
- 设计模式-单例模式
- 指针与野指针
- Dialog的回退按钮的点击事件
- Spring开发环境配置以及入门案例
- 分布式一致性协议学习笔记(一)--Paxos
- Java开发平台下如何区分JDK,Tomcat,eclipse的32位与64版本
- C++ 语法 1. struct 内存的对齐原则
- 使用Slidingmenu爆出“Both setBehindContentView must be called in onCreate in addition to setContentView.”
- iOS Crash之NSFileHandleOperationException