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 a cloneable prototype interface

public interface IPrototype<T>
{
    T Clone();
}

2Step 2: Concrete prototype with deep copy

public class Shape(string type, int x, int y, string color)
    : IPrototype<Shape>
{
    public string Type => type;
    public int X => x;
    public int Y => y;
    public string Color => color;

    public Shape Clone() => new(type, x, y, color);

    public override string ToString() =>
        $"{Type} at ({X},{Y}) color={Color}";
}

3Step 3: Registry of pre-configured prototypes

public class ShapeRegistry
{
    private readonly Dictionary<string, Shape> _prototypes = [];

    public void Register(string key, Shape shape) =>
        _prototypes[key] = shape;

    public Shape Create(string key) =>
        _prototypes.TryGetValue(key, out var proto)
            ? proto.Clone()
            : throw new KeyNotFoundException($"No prototype: {key}");
}

// Usage:
// var registry = new ShapeRegistry();
// registry.Register("red-circle", new Shape("Circle", 0, 0, "Red"));
// var clone = registry.Create("red-circle");

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.