//父类
class Prototype {
protected:
string prototype_name_;
float prototype_field_;
public:
Prototype() {}
Prototype(string prototype_name)
: prototype_name_(prototype_name) {//prototype_name_初始化为prototype_name
}
virtual ~Prototype() {}//析构函数
virtual Prototype* Clone() const = 0;//纯虚函数,使用必须重写
virtual void Method(float prototype_field) {//虚函数,允许被重写
this->prototype_field_ = prototype_field;
std::cout << "Call Method from " << prototype_name_ << " with field : " << prototype_field << std::endl;
}
};
//子类
class Realizetype1 : public Prototype {
private:
float realize_prototype_field1_;//在父类的基础上添加的自己的东西
public:
Realizetype1(string prototype_name, float concrete_prototype_field)//有参构造函数
: Prototype(prototype_name), realize_prototype_field1_(concrete_prototype_field) {
}
/**
* 注意,Clone 方法返回一个新的克隆对象的指针,调用者必须释放其内存。
*/
Prototype* Clone() const override {
return new Realizetype1(*this);
}
};
class Realizetype2 : public Prototype {
private:
float realize_field2_;
public:
Realizetype2(string prototype_name, float concrete_prototype_field)
: Prototype(prototype_name), realize_field2_(concrete_prototype_field) {
}
Prototype* Clone() const override {
return new Realizetype2(*this);
}
};
int main()
{
Realizetype1 sxz("object1", 1000);
Realizetype2 zbj("object2", 800);
Realizetype1* s1 =(Realizetype1*) sxz.Clone();
Realizetype2* z2 = (Realizetype2*)zbj.Clone();
s1->Method(1000);
z2->Method(800);
delete []s1;
delete[]z2;
return 0;
}