CreationalC++verifiedVerified

Prototype Pattern in C++

Creates new objects by cloning an existing instance, avoiding the cost of building from scratch.

How to Implement the Prototype Pattern in C++

1Step 1: Define the Prototype interface

class Shape {
public:
    virtual ~Shape() = default;
    virtual std::unique_ptr<Shape> clone() const = 0;
    virtual std::string describe() const = 0;
};

2Step 2: Concrete prototypes

class Circle : public Shape {
    double radius_;
public:
    explicit Circle(double r) : radius_(r) {}
    std::unique_ptr<Shape> clone() const override {
        return std::make_unique<Circle>(*this);
    }
    std::string describe() const override {
        return "Circle(r=" + std::to_string(radius_) + ")";
    }
};

class Rectangle : public Shape {
    double w_, h_;
public:
    Rectangle(double w, double h) : w_(w), h_(h) {}
    std::unique_ptr<Shape> clone() const override {
        return std::make_unique<Rectangle>(*this);
    }
    std::string describe() const override {
        return "Rect(" + std::to_string(w_) + "x" + std::to_string(h_) + ")";
    }
};

3Step 3: Clone objects without knowing their concrete type

int main() {
    std::unique_ptr<Shape> original = std::make_unique<Circle>(5.0);
    auto copy = original->clone();

    std::cout << "Original: " << original->describe() << "\n";
    std::cout << "Clone:    " << copy->describe() << "\n";
}

Prototype Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Prototype Pattern in the Real World

Think of a cell dividing through mitosis. Instead of building a new cell from raw amino acids, the existing cell duplicates itself — copying its DNA, organelles, and membrane. The result is a fully functional copy produced far faster than assembling one molecule at a time.