原型模式是一种创建型设计模式,它使用一个现有的对象实例作为原型,并通过复制该原型来创建新的对象实例。这种方法避免了每次都需要重新创建复杂对象的问题。
下面是一个简单的 C++11 示例,展示了如何使用原型模式:
假设我们有一个 Shape
类,它代表几何形状,并且可以被复制。我们将创建一个 Shape
类及其派生类 Circle
和 Rectangle
,并且实现一个 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;
}
在这个示例中:
Shape
是一个基类,它定义了一个纯虚函数clone
,用于克隆对象。Circle
和Rectangle
分别是从Shape
派生的类,它们实现了clone
方法,以便克隆自身。draw
方法用于展示如何绘制这些形状。demonstrateCloning
函数展示了如何创建原始形状对象并克隆它们,然后分别绘制原始形状和克隆后的形状。
请注意,这个示例中的 clone
方法使用了浅复制(shallow copy)。如果 Shape
或其派生类包含指针或其他需要深度复制的数据结构,则需要在 clone
方法中实现相应的深复制逻辑。