大话设计模式原型模式c++实现

原型模式

其他二十三种设计模式

#include<iostream>

using namespace std;

//原型模式(Prototype)
class Person {
    
    
public:
	virtual Person* Clone() = 0;
};

class WorkExperience :public Person{
    
    
public:
	WorkExperience() {
    
    }
	~WorkExperience() {
    
    }
	WorkExperience(string _workDate,string _company) {
    
    
		this->workDate = _workDate;
		this->company = _company;
	}
	//深拷贝--拷贝构造函数,使用引用
	WorkExperience(const WorkExperience& r) {
    
      
		workDate = r.workDate;
		company = r.company;
	}
	void DisPlay() {
    
    
		cout << "工作经历: " << workDate << " " << company << endl;
	}
	virtual Person* Clone() {
    
    
		/*浅拷贝
		WorkExperience* tmp = new WorkExperience;
		*tmp = *this;    
		return tmp;*/
		return new WorkExperience(*this);   //调用拷贝构造函数
	}

private:
	string workDate;
	string company;
};

class Resume :public Person {
    
    
public:
	Resume(string _name) {
    
    
		this->name = _name;
	}
	Resume(WorkExperience* _work) {
    
    
		this->work = (WorkExperience*)_work->Clone();
	}
	void SetPersonaInfo(string _sex,string _age) {
    
    
		this->sex = _sex;
		this->age = _age;
	}
	void SetWorkExperience(string _workDate,string _company) {
    
    
		work = new WorkExperience(_workDate, _company);
	}
	void DisPlay() {
    
    
		cout << name << " " << sex << " " << age << endl;
		work->DisPlay();
	}
	virtual Person* Clone() {
    
    
		Resume* obj = new Resume(*this);
		obj->name = this->name;
		obj->sex = this->sex;
		obj->age = this->age;
		return obj;
	}

private:
	string name;
	string sex;
	string age;
	WorkExperience* work;
};

void test1() {
    
    
	Resume* a = new Resume("大鸟");
	a->SetPersonaInfo("男", "29");
	a->SetWorkExperience("1998-2000", "XX公司");

	Resume* b = (Resume*)a->Clone();
	b->SetWorkExperience("1998-2006", "YY公司");

	Resume* c = (Resume*)a->Clone();
	c->SetPersonaInfo("男", "24");
	c->SetWorkExperience("1998-2003", "ZZ公司");

	a->DisPlay();
	b->DisPlay();
	c->DisPlay();

	delete a;
	delete b;
	delete c;
}

int main() {
    
    
	test1();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/wode_0828/article/details/114143731