<aside> 💡
原型模式(Prototype):用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象
</aside>
clone
clone
方法,复制当前对象并返回一个新对象。https://kamacoder.com/problempage.php?pid=1083
#include <iostream>
#include <string>
using namespace std;
// 抽象原型类
class Prototype{
public:
virtual Prototype* clone() const = 0;
virtual void getInfo() const = 0;
};
// 具体原型类
class RectanglePrototype: public Prototype{
public:
RectanglePrototype(string color, int width, int height):
color(color), width(width), height(height){}
Prototype* clone() const override {
// 使用默认的拷贝构造函数
return new RectanglePrototype(*this);
}
void getInfo() const override {
cout << "Color: " << color << ", Width: " << width << ", Height: " << height << endl;
}
private:
string color;
int width;
int height;
};
int main(){
string color;
int width;
int height;
cin >> color >> width >> height;
// 创建原型对象
RectanglePrototype* prototype = new RectanglePrototype(color, width, height);
int n;
cin >> n;
for(int i = 0; i < n; ++i){
// 拷贝原型对象
Prototype* clone = prototype->clone();
clone->getInfo();
delete clone;
}
delete prototype;
return 0;
}