我刚刚开始阅读GO4的书来学习面向对象的概念。为了实践原型模式,我实现了一个小示例(彩色形状的概念取自"refactoring.guru")。下面是我的代码,下面有一些问题。
原型定义:
enum class Shape
{
Circle,
Rectangle,
};
class ColoredShapePrototype
{
protected:
std::string color_;
public:
ColoredShapePrototype() {}
ColoredShapePrototype(std::string color) : color_(color) {}
virtual ~ColoredShapePrototype() {}
virtual ColoredShapePrototype* Clone() const = 0;
virtual void ShapeDetails() { std::cout << "Color: " << color_ << "\n"; }
virtual void UpdateColor(int color) { color_ = color; }
};
class ColoredCirclePrototype : public ColoredShapePrototype
{
private:
int radius_;
public:
ColoredCirclePrototype(std::string color, int raduis) : ColoredShapePrototype(color), radius_(raduis) {}
ColoredShapePrototype* Clone() const override { return new ColoredCirclePrototype(*this); }
void ShapeDetails() { ColoredShapePrototype::ShapeDetails(); std::cout << "Radius: " << radius_ << "\n"; }
};
class ColoredRectanglePrototype : public ColoredShapePrototype
{
private:
int height_;
int width_;
public:
ColoredRectanglePrototype(std::string color, int height, int width) : ColoredShapePrototype(color), height_(height), width_(width) {}
ColoredShapePrototype* Clone() const override { return new ColoredRectanglePrototype(*this); }
void ShapeDetails() { ColoredShapePrototype::ShapeDetails(); std::cout << "Height: " << height_ << "\nWidth:" << width_ << "\n"; }
};
class ShapesPrototypeFactory
{
private:
std::unordered_map<Shape, ColoredShapePrototype*> prototypes_;
public:
ShapesPrototypeFactory() {
prototypes_[Shape::Circle] = new ColoredCirclePrototype("White", 5);
prototypes_[Shape::Rectangle] = new ColoredRectanglePrototype("White", 2, 3);
}
~ShapesPrototypeFactory() {
delete prototypes_[Shape::Circle];
delete prototypes_[Shape::Rectangle];
}
ColoredShapePrototype* CreatePrototype(Shape shape) { return prototypes_[shape]->Clone(); }
};主要用途:
ShapesPrototypeFactory prototype_factory;
ColoredShapePrototype* circ = prototype_factory.CreatePrototype(Shape::Circle);
circ->ShapeDetails();
ColoredShapePrototype* rect = prototype_factory.CreatePrototype(Shape::Rectangle);
rect->ShapeDetails();
delete circ;
delete rect;问题:
提前谢谢,我将非常感谢您的帮助!
发布于 2020-09-02 04:29:16
让我们复习一下你的问题。
https://codereview.stackexchange.com/questions/248553
复制相似问题