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