设计模式——创建型——原型模式

原型模式:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。其中有一个词很重要,那就是拷贝。可以说,拷贝是原型模式的精髓所在。

问题:当对象的构造函数非常复杂,在生成新对象的时候非常耗时间、耗资源的情况

解决方案: 通过复制(克隆、拷贝)一个指定类型的对象来创建更多同类型的对象。这个指定的对象可被称为“原型”对象,也就是通过复制原型对象来得到更多同类型的对象。


#include <iostream>
using namespace std;

class Resume
{
protected:
char* name;// 名字不会变
int age;  //年龄可能会变
public:
Resume()
{
}
virtual ~Resume()
{
}
virtual Resume* Clone()
{
return NULL;
}
virtual void Set(int c_age)  //提供个接口,改变年龄
{
}
virtual void Show()
{
}
};

class ResumeA:public Resume
{
public:
ResumeA(const char* str)  //构造函数
{
if (NULL == str)
{
name = new char[1];
name[0] = '\0';
}
else
{
name = new char[strlen(str)+1];
strcpy(name,str);
}
age = 10;
}
ResumeA(const ResumeA& r) //拷贝构造函数
{
name = new char[strlen((r.name)+1)];
strcpy(name,r.name);
age = r.age;
}
~ResumeA()                //析构函数
{
delete[] name;
}
Resume* Clone()          //克隆
{
return new ResumeA(*this);
}
void Show()              //显示
{
cout<<"ResumeA name:"<<name<<endl;
cout<<"ResumeA age:"<<age<<endl;
}
void Set(int c_age)
{
age = c_age;
}
};

void main()
{
Resume* r1 = new ResumeA("A");
Resume* r3 = r1->Clone();
r1->Show();
delete r1;  //深拷贝,所以对r3无影响。
r1 = NULL;
r3->Set(20);
r3->Show();
return;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值