欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 美景 > C++设计模式 原型模式

C++设计模式 原型模式

2024/10/23 23:23:31 来源:https://blog.csdn.net/semicolon_hello/article/details/142903703  浏览:    关键词:C++设计模式 原型模式

原型模式是一种创建型设计模式,它使用一个现有的对象实例作为原型,并通过复制该原型来创建新的对象实例。这种方法避免了每次都需要重新创建复杂对象的问题。

下面是一个简单的 C++11 示例,展示了如何使用原型模式:

假设我们有一个 Shape 类,它代表几何形状,并且可以被复制。我们将创建一个 Shape 类及其派生类 CircleRectangle,并且实现一个 clone 方法来克隆这些对象。

#include <iostream>
#include <memory>// Base class for shapes
class Shape {
public:virtual ~Shape() {}// Pure virtual function to clone the shapevirtual Shape* clone() const = 0;// Virtual destructor for polymorphic deletionvirtual void draw() const = 0;
};// Derived class representing a Circle
class Circle : public Shape {
public:Circle(int radius) : radius_(radius) {}Shape* clone() const override {return new Circle(*this);}void draw() const override {std::cout << "Drawing Circle with radius: " << radius_ << std::endl;}private:int radius_;
};// Derived class representing a Rectangle
class Rectangle : public Shape {
public:Rectangle(int width, int height) : width_(width), height_(height) {}Shape* clone() const override {return new Rectangle(*this);}void draw() const override {std::cout << "Drawing Rectangle with width: " << width_ << " and height: " << height_ << std::endl;}private:int width_;int height_;
};// Function to demonstrate cloning
void demonstrateCloning() {Circle circle(5);Rectangle rectangle(10, 20);// Clone the shapesShape* clonedCircle = circle.clone();Shape* clonedRectangle = rectangle.clone();// Draw the original and cloned shapescircle.draw();clonedCircle->draw();rectangle.draw();clonedRectangle->draw();// Clean up memorydelete clonedCircle;delete clonedRectangle;
}int main() {demonstrateCloning();return 0;
}

在这个示例中:

  1. Shape 是一个基类,它定义了一个纯虚函数 clone,用于克隆对象。
  2. Circle 和 Rectangle 分别是从 Shape 派生的类,它们实现了 clone 方法,以便克隆自身。
  3. draw 方法用于展示如何绘制这些形状。
  4. demonstrateCloning 函数展示了如何创建原始形状对象并克隆它们,然后分别绘制原始形状和克隆后的形状。

请注意,这个示例中的 clone 方法使用了浅复制(shallow copy)。如果 Shape 或其派生类包含指针或其他需要深度复制的数据结构,则需要在 clone 方法中实现相应的深复制逻辑。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com