标签:
原型模式:
优点:
使用拷贝比new一个对象的开销要小
代码示例:
Prototype.h
#ifndef PROTOTYPE_H #define PROTOTYPE_H /** *1、声明一个抽象基类,并定义clone()函数为纯虚函数。 *2、实例化各个子类,并且实现复制构造函数,并实现clone()函数 */ class Resume { public: Resume(){} virtual ~Resume(){} virtual Resume *clone(){return 0;} virtual void set(char *){} virtual void show(){} protected: char *name; }; class ResumeA : public Resume { public: ResumeA(const char *); ResumeA(const ResumeA &); ~ResumeA(); ResumeA *clone(); void show(); }; class ResumeB : public Resume { public: ResumeB(const char *); ResumeB(const ResumeB &); ~ResumeB(); ResumeB *clone(); void show(); }; #endif // PROTOTYPE_H
#include "prototype.h" #include <string.h> #include <iostream> #include <stdio.h> ResumeA::ResumeA(const char * str) { if(str) { name = new char[1]; name[0] = '\0'; } else { name = new char[strlen(str)+1]; strcpy(name, str); } } ResumeA::ResumeA(const ResumeA &r) { name = new char[strlen(r.name)+1]; strcpy(name, r.name); } ResumeA::~ResumeA() { delete []name; } ResumeA *ResumeA::clone() { return new ResumeA(*this); } void ResumeA::show() { std::cout << "ResumeA name :" << name << std::endl; } ResumeB::ResumeB(const char * str) { if(str) { name = new char[1]; name[0] = '\0'; } else { name = new char[strlen(str)+1]; strcpy(name, str); } } ResumeB::ResumeB(const ResumeB &r) { name = new char[strlen(r.name)+1]; strcpy(name, r.name); } ResumeB::~ResumeB() { delete []name; } ResumeB *ResumeB::clone() { return new ResumeB(*this); } void ResumeB::show() { std::cout << "ResumeB name :" << name << std::endl; }
#include <iostream> #include "prototype.h" int main() { Resume *r1 = new ResumeA("A"); Resume *r2 = new ResumeB("B"); Resume *r3 = r1->clone(); Resume *r4 = r2->clone(); delete r1; delete r2; r3->show(); r4->show(); return 0; }
标签:
原文地址:http://blog.csdn.net/fu1201520/article/details/51330625