本文不讨论原型模式的具体定义
原型模式也叫克隆模式,就是在使用的时候,直接调用该类的接口即可得到该类的一个拷贝。
存在即合理,那为什么要有原型模式呢,我直接在该类上写出拷贝构造函数和赋值构造函数不行吗?
1、为什么不用new一个对象?
答:因为每次new一个对象的花销是很大的,我们在new 的时候是会调用该类的构造函数的,如果构造函数内部的实现比较复杂,那么new 的时间就会比较长。还有个原因是new对象无法获得运行时的状态。
2、为什么不用拷贝构造函数进行克隆?
答:首先得知道我们想要一个对象的副本的时候,可以使用=号或者调用拷贝构造函数将当前的类复制一份。其实和拷贝构造函数的作用是差不多的。(大概的意思就是一般情况是和拷贝构造函数功能差不多的)。那么特殊的情况就是clone是一个接口,可以实现多态的性质,可以使用父类指针克隆到子类对象,而构造函数满足不了。
这里的代码没有实现clone多态的性质
代码:
#include<iostream>
using namespace std;
class Prototype
{
public:
virtual Prototype* Clone()=0;
virtual ~Prototype()
{
cout<<"xigou Prototype"<<endl;
}
};
class concretePrototype:public Prototype
{
private:
string m_a;
public:
concretePrototype(){}
concretePrototype(string a):m_a(a){}
concretePrototype(concretePrototype* pro)
{
this->m_a=pro->m_a;
}
concretePrototype* Clone()
{
return new concretePrototype(this);
}
~concretePrototype()
{
cout<<"xigou concretePrototype"<<endl;
}
friend void client(concretePrototype&);
};
void client(concretePrototype& p)
{
concretePrototype* p1=new concretePrototype;
p1=p.Clone();
cout<<p1->m_a<<endl;
delete p1;
}
/*
abc
xigou concretePrototype
xigou Prototype
xigou concretePrototype
xigou Prototype
*/
int main()
{
concretePrototype* pro=new concretePrototype("abc");
client(*pro);
delete pro;
return 0;
}
实现多态的原型模式:
#include<iostream>
using namespace std;
class Prototype
{
public:
Prototype(){}
Prototype(Prototype* pro)
{
*this=*pro;
}
virtual Prototype* Clone()
{
return new Prototype(this);
}
virtual ~Prototype()
{
cout<<"xigou Prototype"<<endl;
}
};
class concretePrototype:public Prototype
{
private:
public:
concretePrototype(){}
concretePrototype(concretePrototype* pro)
{
*this=*pro;
}
concretePrototype* Clone()
{
return new concretePrototype(this);
}
~concretePrototype()
{
cout<<"xigou concretePrototype"<<endl;
}
friend void client(concretePrototype&);
};
void client(Prototype& p)
{
Prototype* p1=new concretePrototype;
p1=p.Clone();
cout<<&p<<endl;
cout<<p1<<endl;
delete p1;
}
/*
0x14dfc20
0x14dfc60
xigou concretePrototype
xigou Prototype
xigou concretePrototype
xigou Prototype
*/
int main()
{
Prototype* pro=new concretePrototype;
client(*pro);
delete pro;
return 0;
}