Подробнее на 👉 refactoring.guru
Клонируем объект-автомобиль.
#include <iostream>
#include <string>
class CarPrototype {
public:
virtual CarPrototype* clone() = 0;
virtual void info() = 0;
};
class Car : public CarPrototype {
private:
std::string brand;
std::string model;
public:
Car(std::string iBrand, std::string iModel) : brand(iBrand), model(iModel) {}
CarPrototype* clone() { return new Car(*this); }
void info() {
std::cout << "This is a " << brand << " " << model << std::endl;
}
};
int main() {
CarPrototype* prototype = new Car("Toyota", "Camry");
CarPrototype* clone = prototype->clone();
prototype->info();
clone->info();
delete prototype;
delete clone;
return 0;
}
Будет напечатано:
This is a Toyota Camry This is a Toyota Camry
abstract class CarPrototype {
CarPrototype clone();
void info();
}
class Car implements CarPrototype {
String brand;
String model;
Car(this.brand, this.model);
CarPrototype clone() {
return Car(brand, model);
}
void info() {
print('This is a $brand $model');
}
}
void main() {
CarPrototype prototype = Car('Toyota', 'Camry');
CarPrototype clone = prototype.clone();
prototype.info();
clone.info();
}
Будет напечатано:
This is a Toyota Camry This is a Toyota Camry