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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

semicolon_helloword

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值