Prototype

Creates new objects by cloning an existing instance, avoiding reliance on its concrete classes.

Context

You need to duplicate objects whose configuration is costly to reproduce or whose construction depends on private state to which you do not have access.

Problem
  • Copying field-by-field from outside violates encapsulation.
  • new requires knowing the concrete class and replicating all steps.
Solution

Each object knows how to clone itself (Clone()), returning an independent copy.

#Example in C#

public abstract record Shape
{
    public int X { get; init; }
    public int Y { get; init; }
    public string Color { get; init; } = "black";

    public abstract Shape Clone();
}

public sealed record Circle(int X, int Y, string Color, int Radius) : Shape
{
    public override Shape Clone() => this with { };  // free shallow copy
}

In modern C#, record types already implement with, which is semantically a Prototype.

When NOT to use it
  • When the object contains deep references that require non-trivial recursive cloning.
  • When you can simply serialize/deserialize.
Tradeoffs
Pro Con
Independence from concrete classes Deep cloning is difficult to maintain
Speed when construction is expensive Risk of aliasing if copy is shallow

#creational #gof #clone