码迷,mamicode.com
首页 > 编程语言 > 详细

python 设计模式之 单例模式

时间:2015-12-26 19:36:51      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:

单例模式是做为"全局变量"的替代品出现的。所以它具有全局变量的特点:全局可见、贯穿应用程序的整个生命期,保证在程序执行中,某个类仅仅存在一个实例,所以通常不希望类中的构造函数被调用

 

python:

 

class Single(object):
	instance = None	
	#
	def __init__(self):
		pass
	#
	def getInstance(self):
		if Single.instance == None:
			Single.instance = Single()
		return Single.instance
	#
	def printSelf(self):
		if Single.instance != None:
			print Single.instance

s = Single()
s1 = s.getInstance()
s2 = s.getInstance()
s1.printSelf()
s2.printSelf()</span>

C++:

Single.h

ifndef __SINGLE_H
#define __SINGLE_H

class Single
{
private:
	static Single *instance;

	Single();

public:
	static Single* getInstance();
	void printSelf();
};

#endif


Single.cpp

#include "Single.h"
#include <iostream>

Single* Single::instance = NULL;

Single::Single()
{
}

Single* Single::getInstance()
{
	if (!instance)
		instance = new Single;

	return instance;
}

void Single::printSelf()
{
	if (instance)
		std::cout << instance << std::endl;
}


 

#include "Single.h"

int main()
{
	Single::getInstance()->printSelf();
	Single *sin = Single::getInstance();
	sin->printSelf();
	return  0;
}


 

 

 

python 设计模式之 单例模式

标签:

原文地址:http://www.cnblogs.com/gcczhongduan/p/5078567.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!