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()</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; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。