用原型實例指定創建對象的種類,並且通過拷貝這些原型創建新的對象。
基本介紹
定義
解決問題
如何使用
public abstract class AbstractSpoon implements Cloneable{String spoonName;public void setSpoonName(String spoonName) {this.spoonName = spoonName;}public String getSpoonName() {return this.spoonName;}public Object clone(){Object object = null;try {object = super.clone();} catch (CloneNotSupportedException exception) {System.err.println("AbstractSpoon is not Cloneable");}return object;}}有兩個具體實現(ConcretePrototype):public class SoupSpoon extends AbstractSpoon{public SoupSpoon(){setSpoonName("Soup Spoon");}}
AbstractSpoon spoon = new SoupSpoon();AbstractSpoon spoon = new SaladSpoon();
/ CplusplusPrototype.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include<iostream>#include<vector>#include<assert.h>usingnamespace std;//父類class Resume{protected:char *name;public:Resume() {}virtual ~Resume() {}virtual Resume* Clone() { return NULL; }virtualvoid Set(char *n) {}virtualvoid Show() {}};class ResumeA : public Resume{public:ResumeA(constchar *str); //構造函式ResumeA(const ResumeA &r); //拷貝構造函式~ResumeA(); //析構函式ResumeA* Clone(); //克隆,關鍵所在void Show(); //顯示內容};ResumeA::ResumeA(constchar *str){if(str == NULL) {name = newchar[1];name[0] = '\0';}else {name = newchar[strlen(str)+1];strcpy(name, str);}}ResumeA::~ResumeA() { delete [] name;}ResumeA::ResumeA(const ResumeA &r) {name = newchar[strlen(r.name)+1];strcpy(name, r.name);}ResumeA* ResumeA::Clone() {returnnew ResumeA(*this);}void ResumeA::Show() {cout<<"ResumeA name : "<<name<<endl;}class ResumeB : public Resume{public:ResumeB(constchar *str); //構造函式ResumeB(const ResumeB &r); //拷貝構造函式~ResumeB(); //析構函式ResumeB* Clone(); //克隆,關鍵所在void Show(); //顯示內容};ResumeB::ResumeB(constchar *str){if(str == NULL) {name = newchar[1];name[0] = '\0';}else {name = newchar[strlen(str)+1];strcpy(name, str);}}ResumeB::~ResumeB() { delete [] name;}ResumeB::ResumeB(const ResumeB &r) {name = newchar[strlen(r.name)+1];strcpy(name, r.name);}ResumeB* ResumeB::Clone() {returnnew ResumeB(*this);}void ResumeB::Show() {cout<<"ResumeB name : "<<name<<endl;}class ResumeManager{private:vector<Resume *> mResume;public:ResumeManager(){}void add(Resume * resume){mResume.push_back(resume);}Resume * get(int index) const{assert(index>=0 && index<mResume.size());return mResume[index];}};int _tmain(int argc, _TCHAR* argv[]){ResumeManager *manager = new ResumeManager();Resume *r1 = new ResumeA("A");Resume *r2 = new ResumeB("B");manager->add(r1);manager->add(r2);manager->get(0)->Show();manager->get(1)->Show();Resume *r3 = manager->get(0)->Clone();Resume *r4 = manager->get(1)->Clone();//刪除r1,r2delete r1; delete r2;r1 = r2 = NULL;//深拷貝所以對r3,r4無影響r3->Show(); r4->Show();delete r3; delete r4;r3 = r4 = NULL;return 0;}