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中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm
《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm
Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm
在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm
Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm
Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡