设计模式:单例模式

目的:怎样去创建一个唯一的变量(对象)?在基于对象的设计中我们可以通过创建一个全局变量(对象)来实现,在面向对象和面向过程结合的设计范式(如C++中)中,我们也还是可以通过一个全局变量实现这一点。但是当我们遇到了纯粹的面向对象范式中,这一点可能就只能是通过Singleton模式来实现了。


注意:

1. 在默认构造函数Singleton()访问类型是protected(或private)

2. public: static Singleton* Instance();

3. private: static Singleton* _instance;

4. Singleton* Singleton::_instance = 0;

5.Singleton *sgn = Singleton::Instance();




代码(来自设计模式精解-Gof 23 种设计模式解析), 在VS2010上调试通过

//Singleton.h

#ifndef SINGLETON_H
#define SINGLETON_H

#include <iostream>

class Singleton
{
public:
	static Singleton* Instance();

protected:
	Singleton();

private:
	static Singleton* _instance;
};


#endif


//Singleton.cpp

#include "Singleton.h"

Singleton* Singleton::_instance = 0;

Singleton::Singleton()
{
	std::cout<<"Singleton ..."<<std::endl;
}

Singleton* Singleton::Instance()
{
	if(0 == _instance)
	{
		_instance = new Singleton();
	}

	return _instance;
}

//main.cpp

#include "Singleton.h"

int main(int argc, char* argv[])
{
	Singleton *sgn = Singleton::Instance();

	delete sgn;
	sgn = 0;

	system("pause");
	return 0;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值