设计模式-原型模式 C++实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhao5502169/article/details/89263211

原型模式

定义:用一个已经创建的实例作为原型,通过拷贝该原型对象来创建一个和原型相同的新对象。

原型模式的克隆分为浅克隆和深克隆;
浅克隆:创建一个新对象,对于非基本类型属性,仍指向原有属性所指向的对象的内存地址。
深克隆:创建一个新对象,属性中指向的其他对象也被拷贝了一份。

C++实现,这里的Clone()是深克隆

Prototype.h
#pragma once
class Prototype {
public:
	Prototype();
	virtual ~Prototype();
	virtual Prototype* Clone() = 0;
	virtual void show() = 0;
};

Prototype.cpp
#include"Prototype.h"
#include<iostream>

using namespace std;

Prototype::Prototype() {
	cout << "Prototype" << endl;
}
Prototype::~Prototype() {
	cout << "~Prototype" << endl;
}

ConcretePrototype.h
#pragma once
#include"Prototype.h"
#include<string>

using namespace std;
class ConcretePrototype :public Prototype {
public:
	ConcretePrototype(string _str_name);
	~ConcretePrototype();
	ConcretePrototype(const ConcretePrototype& other);
	Prototype* Clone();
	void show();
private:
	string str_name;
};
ConcretePrototype.cpp
#include"ConcretePrototype.h"
#include"Prototype.h"
#include<iostream>

using namespace std;

ConcretePrototype::ConcretePrototype(string _str_name) {
	this->str_name = _str_name;
	cout << "ConcretePrototype" << endl;
}
ConcretePrototype::ConcretePrototype(const ConcretePrototype& other) {
	this->str_name = other.str_name;
}
void ConcretePrototype::show() {
	cout << "name:" << this->str_name << endl;
}
ConcretePrototype::~ConcretePrototype() {
	cout << "~ConcretePrototype" << endl;
}
Prototype* ConcretePrototype::Clone() {
	return new ConcretePrototype(*this);
}
main.cpp
#include"Prototype.h"
#include"ConcretePrototype.h"
#include<iostream>
using namespace std;

int main(void) {
	Prototype* pm = new ConcretePrototype("henuzxy");
	pm->show();
	//Clone
	Prototype* p1 = pm->Clone();
	Prototype* p2 = pm->Clone();
	p1->show();
	p2->show();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/zhao5502169/article/details/89263211