如果您无法下载资料,请参考说明:
1、部分资料下载需要金币,请确保您的账户上有足够的金币
2、已购买过的文档,再次下载不重复扣费
3、资料包下载后请先用软件解压,在使用对应软件打开
HYPERLINK"http://blog.csdn.net/wuzhekai1985/article/details/6665869"设计模式C++实现(4)——单例模式分类:HYPERLINK"http://blog.csdn.net/wuzhekai1985/article/category/859763"设计模式2011-08-0622:082494人阅读HYPERLINK"http://blog.csdn.net/wuzhekai1985/article/details/6665869"\l"comments"评论(9)HYPERLINK"javascript:void(0);"\o"收藏"收藏HYPERLINK"http://blog.csdn.net/wuzhekai1985/article/details/6665869"\l"report"\o"举报"举报软件领域中的设计模式为开发人员提供了一种使用专家设计经验的有效途径。设计模式中运用了面向对象编程语言的重要特性:封装、继承、多态,真正领悟设计模式的精髓是可能一个漫长的过程,需要大量实践经验的积累。最近看设计模式的书,对于每个模式,用C++写了个小例子,加深一下理解。主要参考《大话设计模式》和《设计模式:可复用面向对象软件的基础》(DP)两本书。本文介绍单例模式的实现。单例的一般实现比较简单,下面是代码和UML图。由于构造函数是私有的,因此无法通过构造函数实例化,唯一的方法就是通过调用静态函数GetInstance。UML图:代码:[cpp]HYPERLINK"http://blog.csdn.net/wuzhekai1985/article/details/6665869"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/wuzhekai1985/article/details/6665869"\o"copy"copyHYPERLINK"http://blog.csdn.net/wuzhekai1985/article/details/6665869"\o"print"printHYPERLINK"http://blog.csdn.net/wuzhekai1985/article/details/6665869"\o"?"?//Singleton.hclassSingleton{public:staticSingleton*GetInstance();private:Singleton(){}staticSingleton*singleton;};//Singleton.cppSingleton*Singleton::singleton=NULL;Singleton*Singleton::GetInstance(){if(singleton==NULL)singleton=newSingleton();returnsingleton;}这里只有一个类,如何实现Singleton类的子类呢?也就说Singleton有很多子类,在一种应用中,只选择其中的一个。最容易就是在GetInstance函数中做判断,比如可以传递一个字符串,根据字符串的内容创建相应的子类实例。这也是DP书上的一种解法,书上给的代码不全。这里重新实现了一下,发现不是想象中的那么简单,最后实现的版本看上去很怪异。在VS2008下测试通过。[cpp]HYPERLINK"http://blog.csdn.net/wuzhekai1985/article/details/6665869"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/wuzhekai1985/article/details/6665869"\o"copy"copyHYPERLINK"http://blog.csdn.net/wuzhekai1985/article/details/6665869"\o"print"printHYPERLINK"http://blog.csdn.net/wuzhekai1985/article/details/6665869"\o"?"?//Singleton.h#pragmaonce#include<iostream>usingnamespacestd;classSingleton{public:staticSingleton*GetInstance(constchar*name);virtualvoidShow(){}protecte