原型模式属于我们要介绍的创建型模式的最后一种。火影中,鸣人的绝招之一就是影分身之术,复制出大量的自己,在某个程度上我们也可以看做是原型模式,因为影子分身也是单独存在的,只是比较脆弱一点。。原型模式相对比较容易理解,即为已经存在的类新增一个克隆的接口,所谓的克隆就是产生一个与自身无关、单独存在的个体。在c++ 中我们通常用拷贝构造函数来实现这个原型模式,因此我们有必要先理解何为拷贝构造函数以及浅拷贝、深拷贝(下一篇介绍)。
Prototype 结构图:
简单的代码实现为:
/* @file: CPrototype.h @brief: 原型模式头文件 @author: 糙级码lee @create date:2012-10-07 版权说明: 本代码版权 为 糙级码lee 所有 转载请注明来自:http://blog.csdn.net/zerolxl */ #ifndef _C__PROTOTYPE_H_ #define _C__PROTOTYPE_H_ #include <string> #include <iostream> class CPrototypeBase { public: CPrototypeBase(){} virtual ~CPrototypeBase(){} virtual CPrototypeBase* Clone()=0; virtual void ShowSelf() =0; protected: std::string m_strIntroduce; }; class CPrototypeA:public CPrototypeBase { public: CPrototypeA() { m_strIntroduce="this is CPrototypeA"; } CPrototypeA(const CPrototypeA & cPa) { m_strIntroduce="i have my life."; std::cout<<"CPrototypeA clone ..."<<std::endl; } virtual ~CPrototypeA(){} virtual CPrototypeA* Clone() { return new CPrototypeA( *this); } void ShowSelf() { std::cout << m_strIntroduce <<std::endl; } }; #endif //_C__PROTOTYPE_H_
客户端代码:
// prototype.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "stdio.h" #include "CPrototype.h" int _tmain(int argc, _TCHAR* argv[]) { CPrototypeBase *p=new CPrototypeA; p->ShowSelf(); CPrototypeBase *pClone=p->Clone(); pClone->ShowSelf(); getchar(); return 0; }
输出:
自此我们可已经将创建型的几种设计模式都学习了一片。通过这次的整理自己对于这几个模式也有了一个相对比较系统的认识(说的不对之处欢迎批评拍砖)。Prototype模式通过复制原型(Prototype)而获得新对象创建的功能,上面代码 Prototype本身就是“对象工厂”(因为能够生产对象),实际上Prototype模式和Builder模式、AbstractFactory模式都是通过一个类(对象实例)来专门负责对象的创建工作(工厂对象),单例模式则是通过一个接口返回唯一的实例接口(也相当于创建了一个特殊的对象),因此他们都被归类为创建型里面,它们之间的区别是:Builder模式重在复杂对象的一步步创建(并不直接返回对象),AbstractFactory模式重在产生多个相互依赖类的对象,而Prototype模式重在从自身复制自己创建新类。