当前位置: 首页 > article >正文

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 shape
    virtual Shape* clone() const = 0;

    // Virtual destructor for polymorphic deletion
    virtual 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 shapes
    Shape* clonedCircle = circle.clone();
    Shape* clonedRectangle = rectangle.clone();

    // Draw the original and cloned shapes
    circle.draw();
    clonedCircle->draw();

    rectangle.draw();
    clonedRectangle->draw();

    // Clean up memory
    delete 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 方法中实现相应的深复制逻辑。


http://www.kler.cn/news/354347.html

相关文章:

  • spring boot热部署
  • “vue : 无法加载文件 D:\nodejs\node_global\vue.ps1,因为在此系统上禁止运行脚本”的解决方法
  • 基于php的图书管理系统
  • 录微课专用提词器,不会被录进视频中的提词器,还能显示PPT中备注的内容
  • 图书管理新趋势:Spring Boot进销存系统
  • 涂鸦智能落地 Koupleless 合并部署,实现云服务降本增效
  • [含文档+PPT+源码等]精品大数据项目-python基于hadoop实现的社交媒体数据分析和用户行为预测
  • Okhttp3中设置超时的方法
  • React前端框架高级技巧
  • 分布式数据库的进度管理:TiDB 备份恢复工具 PiTR 的原理与实践
  • 【数据结构】二叉堆一文详解,附demo
  • android studio confirauration中 install flags和launch flags区别
  • 海思hi3536c配置内核支持USB摄像头
  • Elasticsearch入门:增删改查详解与实用场景
  • 数据结构编程实践20讲(Python版)—16有向图
  • 前端面试题16 | Http和Https相比,有什么区别?
  • repo 命令大全详解(第十一篇 repo init)
  • 什么叫IDS
  • 【数据集】香港数据收集:气象站点、DTM等
  • 大舍传媒-海外媒体发稿:为您打造全球品牌影响力