原型模式(Prototype Pattern)是一种创建型设计模式,其主要思想是通过复制(克隆)现有对象来创建新的对象,而不是通过构造函数创建。这样可以避免重复创建相似对象时的性能损耗,同时也更灵活,可以动态地添加或删除对象。原型模式的性能优势主要来自于避免了重复的初始化和构造过程。在原型模式中,对象的克隆是通过复制已有对象的数据而不是重新构造对象,因此避免了重复的初始化和资源获取操作,提高了性能。
在原型模式中,有一个原型对象,它是被复制的对象。通过克隆原型对象,可以创建新的对象,并且可以通过改变克隆的属性来实现个性化定制。在使用原型模式时,通常会提供一个克隆方法,用于复制对象。
原型模式在以下情况下特别有用,可以提高性能并提供更灵活的设计:
需要注意的是,虽然原型模式可以提高性能,但在一些情况下可能引入对象状态的共享,因此在设计时需要确保克隆的对象是独立的,不会相互影响。此外,如果原型对象包含引用类型的成员变量,需要特别注意深克隆,以防止共享引用类型对象的问题。
简单实现如下。有一个抽象基类 Prototype
,它定义了 clone()
和 print()
这两个虚函数。PrototypeClass
是具体的原型类,它继承了 Prototype
并实现了这两个虚函数。在 PrototypeClass
中,它实现了深拷贝构造函数和克隆接口。深拷贝构造函数用于创建一个新的对象并拷贝原始对象的数据,而克隆接口 clone()
则是通过调用深拷贝构造函数创建一个新的对象并返回。
#include <iostream>
#include <cstring>
class PrototypeClass;
class Prototype;
class Prototype
{
public:
virtual Prototype *clone() = 0;
virtual void print() = 0;
};
class PrototypeClass : public Prototype
{
private:
char *str;
public:
PrototypeClass(const char *str)
{
this->str = new char[strlen(str) + 1];
strcpy(this->str, str);
};
PrototypeClass(PrototypeClass &pc)
{
// 深拷贝
delete[] str;
this->str = new char[strlen(pc.str) + 1];
strcpy(this->str, pc.str);
}
Prototype *clone() override
{
// 克隆接口
return new PrototypeClass(*this);
}
void print()
{
std::cout << str << std::endl;
}
~PrototypeClass()
{
delete[] str;
};
};
int main(int argc, char const *argv[])
{
PrototypeClass *p1 = new PrototypeClass("Hello world!");
p1->print();
// 拷贝构造函数
PrototypeClass *p2 = p1;
p2->print();
// 克隆接口
Prototype *p3 = p1->clone();
p3->print();
return 0;
}
.post-copyright { box-shadow: 2px 2px 5px; line-height: 2; position: relative; margin: 40px 0 10px; padding: 10px 16px; border: 1px solid var(--light-grey); transition: box-shadow .3s ease-in-out; overflow: hidden; border-radius: 12px!important; background-color: var(--main-bg-color); } .post-copyright:before { position: absolute; right: -26px; top: -120px; content: '\f25e'; font-size: 200px; font-family: 'FontAwesome'; opacity: .2; } .post-copyright__title { font-size: 22px; } .post-copyright_type { font-size: 18px; color:var(--theme-color) } .post-copyright .post-copyright-info { padding-left: 6px; font-size: 15px; } .post-copyright-m-info .post-copyright-a, .post-copyright-m-info .post-copyright-c, .post-copyright-m-info .post-copyright-u { display: inline-block; width: fit-content; padding: 2px 5px; font-size: 15px; } .muted-3-color { color: var(--main-color); } /*手机优化*/ @media screen and (max-width:800px){.post-copyright-m-info{display:none}} ------本页内容已结束,喜欢请分享------