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

原型模式

定义:用一个已经创建的实例作为原型,通过拷贝该原型对象来创建一个和原型相同的新对象。
原型模式的克隆分为浅克隆和深克隆;
浅克隆:创建一个新对象,对于非基本类型属性,仍指向原有属性所指向的对象的内存地址。
深克隆:创建一个新对象,属性中指向的其他对象也被拷贝了一份。
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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值