9.3 原型模式:
#include<iostream>
#include<string>
using namespace std;
/*
用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象,原型模式实际上就是从一个对象再创建另外一个可定制的对象,而且不需要知道任何创建的细节
一般在初始化信息不发生变化的情况下,克隆是最好的办法。这样既隐藏了对象创建的细节,又对性能是大大的提高。不用重新初始化对象,而是动态的获得对象运行时的状态
其中利用java的memberwiseClone()方法,如果字段是值类型的,则对字段执行逐位复制,如果字段是引用类型,则复制引用但不复制引用的对象,因此,
原始对象及其副本引用同一对象
*/
//抽象的原型类
class Prototype
{
public:
//在抽象类中定义拷贝对象的接口
virtual Prototype* Clone() = 0;
virtual void Display() = 0;
};
//子类访问父类成员,父类成员必须是protected或者public的
class ConcretePrototype1 : public Prototype
{
private:
string id;
public:
ConcretePrototype1()
{
this->id = "";
}
ConcretePrototype1(string id)
{
this->id = id;
}
//提供具体的构造方法
virtual Prototype* Clone()
{
ConcretePrototype1 *p = new ConcretePrototype1();
*p = *this;
return p;
}
virtual void Display()
{
cout << "Id: " << this->id << endl;
}
string DisplayId()
{
return this->id;
}
};
void Client()
{
ConcretePrototype1 *p1 = new ConcretePrototype1("wuyu");
Prototype *c1 = p1->Clone();
c1->Display();
}
int main()
{
Client();
system("pause");
return EXIT_SUCCESS;
}
9.4 简历原型的实现
#include<iostream>
#include<string>
using namespace std;
class ICloneable
{
public:
virtual void SetPersonalInfo(string sex, string age) = 0;
virtual void SetWorkExperience(string timeArea, string company) = 0;
virtual void Display() = 0;
virtual ICloneable* Clone() = 0;
virtual ICloneable* CloneShallow() = 0;
};
class Resume : public ICloneable
{
private:
string name;
string sex;
string age;
string timeArea;
string company;
public:
Resume()
{
}
Resume(string name)
{
this->name = name;
}
virtual void SetPersonalInfo(string sex, string age)
{
this->sex = sex;
this->age = age;
}
virtual void SetWorkExperience(string timeArea, string company)
{
this->timeArea = timeArea;
this->company = company;
}
virtual void Display()
{
cout << "名字: " << this->name << endl;
cout << "性别: " << this->sex << " 年龄: " << this->age << endl;
cout << "时间: " << this->age << " 地点: " << this->company << endl;
}
virtual ICloneable* Clone()
{
Resume *p = new Resume();
*p = *this;
return p;
}
virtual ICloneable* CloneShallow()
{
Resume *p = this;
return p;
}
};
void Client()
{
Resume *a = new Resume("大鸟");
a->SetPersonalInfo("雄性", "24");
a->SetWorkExperience("2011-2014", "成都市");
Resume *b = (Resume*)a->Clone();
b->SetWorkExperience("2014-2016", "白宫");
Resume *c = (Resume*)a->Clone();
c->SetPersonalInfo("雌性", "18");
//看看abc的地址
cout << a << endl << b << endl << c << endl;
a->Display();
b->Display();
c->Display();
//查看浅拷贝
Resume *d = (Resume*)a->CloneShallow();
d->SetPersonalInfo("雌性", "18");
d->Display();
//查看d的地址
cout << "d的地址: " << d << endl;
if (a != NULL)
{
delete a;
a = NULL;
}
if (b != NULL)
{
delete b;
b = NULL;
}
if (c != NULL)
{
delete c;
c = NULL;
}
//再次释放d的地址将会导致错误
//if (d != NULL)
//{
// delete d;
// d = NULL;
//}
}
int main()
{
Client();
system("pause");
return EXIT_SUCCESS;
}