原型模式的定义
c++中的原型模式(Prototype Pattern)是一种创建型设计模式,其目的是通过复制(克隆)已有对象来创建新的对象,而不需要显示的使用构造函数创建对象,原型模式适用于创建复杂对象时,避免构造函数的重复调用和初始化步骤,提高了对象创建的效率。
 在c++中实现原型模式,可以通过一下步骤:
 1.创建一个抽象基类,作为原型类,其中定义一个纯虚函数clone(),用于克隆对象。
 2.派生具体的类,并实现clone()函数,在clone函数中,创建当前实例的副本,并返回指向副本的指针。
 3.在客户端代码中,通过调用原型对象的clone()函数来获取新的对象。
 注:类的默认考本构造函数是浅拷贝,我们实现的clone()函数是深拷贝。
实例
#include <iostream>
using namespace std;
//抽象原型类
class Prototype
{
public:
	virtual Prototype* clone() const = 0;
	virtual void display() = 0;
};
//具体原型类1
class ConcretePrototype1 :public Prototype
{
public:
	Prototype* clone() const
	{
		return new ConcretePrototype1(*this);
	}
	void display()
	{
		cout << "我是ConcretePrototype1" << endl;
	}
};
//具体原型类2
class ConcretePrototype2 :public Prototype
{
public:
	Prototype* clone() const
	{
		return new ConcretePrototype2(*this);
	}
	void display()
	{
		cout << "我是ConcretePrototype2" << endl;
	}
};
int main()
{
	ConcretePrototype1 c1;
	Prototype*  cc1  = c1.clone();
	cc1->display();
	ConcretePrototype2 c2;
	Prototype* cc2 = c2.clone();
	cc2->display();
	return 0;
}
















![[每日算法 - 阿里机试] leetcode19. 删除链表的倒数第 N 个结点](https://img-blog.csdnimg.cn/25527a7b352845cc8f14a6e62da1e8e9.png)



