Python单例模式是做为"全局变量"的替代品出现的。所以它具有全局变量的特点:全局可见、贯穿应用程序的整个生命期,保证在程序运行中,某个类只存在一个实例,所以通常不希望类中的构造函数被调用。
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()
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核心编程 第二版》.(Wesley J. Chun ).[高清PDF中文版]
《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码]
在Ubuntu下用Python搭建桌面算法交易研究环境