python 设计模式之 单例模式
2015-12-26 18:43
621 查看
单例模式是做为"全局变量"的替代品出现的。所以它具有全局变量的特点:全局可见、贯穿应用程序的整个生命期,保证在程序执行中,某个类仅仅存在一个实例,所以通常不希望类中的构造函数被调用
python:
C++:
Single.h
Single.cpp
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; }
相关文章推荐
- Windows下python的配置
- python学习1(小白记录)
- 使用Python递归在根目录下面写入文件
- python基础----装饰器
- python实现了字符串的按位异或和php中的strpad函数
- python数据可视化--散点图以及分类
- 读书笔记--python数据可视化--003_读取定宽数据文件
- python的utc8小时时间问题
- [Python]打印a..z的字符
- 读书笔记--python数据可视化--002_读取Excel文件数据
- Python Argparse 简易指南
- python sys.exit()函数说明
- python生成u8glib中文字体数据
- python之各种二分查找
- Python优秀函数库集锦(一)
- 读书笔记--python数据可视化--001_读取CSV文件数据
- python json
- Python:字符串、列表和元组
- python中实现多线程的几种方式
- python-web加载性能测试(初级)