首页 > 编程语言 > 详细

设计模式学习笔记c++版——单例模式

时间:2016-01-07 13:39:30      阅读:188      评论:0      收藏:0      [点我收藏+]

特别注意单例模式c++实现在main.cpp中引用的时候要去申明下:

Singleton * Singleton::m_Instance = NULL; //定义性声明

不然会报错:无法解析的外部符号 "private: static class Singleton * Singleton::m_Instance" 之类的。

以下是一个很简单的单例模式的测试demo,这个模式并没有考虑并发的问题。如果是并发,可以考虑在创建对象的时候加锁

stdafx.h

#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
#include <iostream>
using namespace std;

Singleton.h

#pragma once
#include "stdafx.h"
class Singleton
{
public:
	static Singleton * GetInstance();

	void Add();
	void MyPrint(string str);

private:
	Singleton();
	~Singleton();

	static Singleton * m_Instance;
	int intNum;
};

Singleton.cpp

#include "stdafx.h"
#include "Singleton.h"

Singleton* Singleton::GetInstance()
{
	if (m_Instance == NULL)
	{
		m_Instance = new Singleton();
	}
	return m_Instance;
}

void Singleton::MyPrint(string str)
{
	printf("%s\n",str.c_str());
}

void Singleton::Add()
{
	intNum++;
	printf("intNum=%d\n", intNum);
}

Singleton::Singleton()
{
	intNum = 0;
}

Singleton::~Singleton()
{
}

 

main.cpp

// c++单例模式 2016/1/7 dgx

#include "stdafx.h"
#include "Singleton.h"

Singleton * Singleton::m_Instance = NULL; //定义性声明 
int main(int argc, char *argv[])
{
	Singleton *singletonObj = Singleton::GetInstance();
	singletonObj->MyPrint("Hello Singleton!");
	singletonObj->Add();

	for (int i = 0; i < 10; i++)
	{
		Singleton * singletonObj2 = Singleton::GetInstance();
		singletonObj2->Add();
	}
	
	getchar();
	return 0;
}

 技术分享技术分享

设计模式学习笔记c++版——单例模式

原文:http://www.cnblogs.com/duguxue/p/5109436.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!