Polski

Article · Prototype · Abstract Factory

Prototype – a new object as a copy of a ready-made template

Prototype creates objects by cloning a configured instance instead of building them from scratch. We explain the difference between shallow and deep copies using exam templates as an example.

By · · 10 min read

Sometimes the easiest way to create an object is to take a similar one and change a few details. Prototype turns this into a pattern: the object knows how to copy itself, and code that needs a new instance does not have to know its class or all of its configuration parameters.

The problem: an exam for group B

On a programming course platform, an instructor prepares an exam: a title, a time limit, dozens of questions, each with a list of answers, and shuffling settings. For group B they want the same exam with two answers changed. The first version of the "Duplicate" feature looked like this:

duplicate-exam.ts
function duplicate(exam: Exam): Exam {
  // copies the fields, but the questions array is the same object!
  return { ...exam, title: exam.title + " (copy)" };
}

const groupB = duplicate(midterm);
groupB.questions[3].options.push("None of the above"); // midterm changes too

The spread operator copies only the first level. The question list is shared, so editing group B's version silently changes group A's exam – and the bug surfaces only when students see an answer that should not be there. The second problem: the duplicating code has to know every field of the exam and must be updated whenever the class changes.

The solution: an object that can clone itself

We move the responsibility for copying into the object itself. Exam.clone() knows which fields can be copied directly (title, time limit) and which must be cloned recursively (questions, and the answer lists inside them). Ready-made templates – "midterm", "final exam", "warm-up quiz" – live in a registry and are cloned instead of built from scratch.

Diagram: Prototype with a template registry
RoleIn the exampleResponsibility
PrototypeIPrototype<T>declares the cloning operation
Concrete prototypeExam, Questionimplements the copy and decides its depth
Registry (optional)a dictionary of templatesstores configured prototypes by name
Clientthe "Duplicate exam" viewasks for a copy without knowing construction details

Shallow or deep copy?

This is the heart of the pattern. A shallow copy creates a new object, but fields that point to other objects still point to the same instances. A deep copy recursively copies nested objects as well. Immutable fields – strings, numbers, records without setters – can be shared safely; collections and mutable objects must be cloned.

Diagram: A shallow copy shares the question list, a deep copy has its own

Implementation in five languages

Each language has its traps here: a C# record with with and Python's dataclasses.replace() make shallow copies, so does TypeScript's spread operator, and in Go assigning a struct copies it, but slices still point to the same backing array. That is why every implementation clones collections explicitly.

Exam.Clone()

Exams.cs
var registry = new Dictionary<string, Exam>
{
    ["midterm"] = new Exam("Midterm", TimeSpan.FromMinutes(45),
        [new Question("What does SRP stand for?", ["Single Responsibility", "Simple Routing"])]),
};

var groupA = registry["midterm"].Clone();
groupA.Title = "Midterm - group A";
groupA.Questions[0].Options.Add("Strict Rendering Pipeline");

var template = registry["midterm"];
Console.WriteLine($"{template.Questions[0].Options.Count} vs {groupA.Questions[0].Options.Count}");

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

public sealed class Question(string text, List<string> options) : IPrototype<Question>
{
    public string Text { get; set; } = text;
    public List<string> Options { get; } = options;

    public Question Clone() => new(Text, [.. Options]);
}

public sealed class Exam(string title, TimeSpan timeLimit, List<Question> questions)
    : IPrototype<Exam>
{
    public string Title { get; set; } = title;
    public TimeSpan TimeLimit { get; set; } = timeLimit;
    public List<Question> Questions { get; } = questions;

    // Deep copy: the clone gets its own questions, so editing it never touches the template.
    public Exam Clone() => new(Title, TimeLimit, Questions.Select(q => q.Clone()).ToList());
}
exams.ts
class Question {
  constructor(public text: string, public readonly options: string[]) {}

  clone(): Question {
    return new Question(this.text, [...this.options]);
  }
}

class Exam {
  constructor(
    public title: string,
    public timeLimitMin: number,
    public readonly questions: Question[],
  ) {}

  // Deep copy: the clone gets its own questions, so editing it never touches the template.
  clone(): Exam {
    return new Exam(this.title, this.timeLimitMin, this.questions.map((q) => q.clone()));
  }
}

const registry = new Map<string, Exam>([
  [
    "midterm",
    new Exam("Midterm", 45, [
      new Question("What does SRP stand for?", ["Single Responsibility", "Simple Routing"]),
    ]),
  ],
]);

const template = registry.get("midterm")!;
const groupA = template.clone();
groupA.title = "Midterm - group A";
groupA.questions[0].options.push("Strict Rendering Pipeline");
console.log(template.questions[0].options.length, groupA.questions[0].options.length); // 2 3
Exams.java
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

final class Question {
    String text;
    final List<String> options;

    Question(String text, List<String> options) {
        this.text = text;
        this.options = new ArrayList<>(options);
    }

    // Copy constructors/methods are the idiomatic Java alternative to Cloneable.
    Question copy() { return new Question(text, options); }
}

final class Exam {
    String title;
    int timeLimitMin;
    final List<Question> questions;

    Exam(String title, int timeLimitMin, List<Question> questions) {
        this.title = title;
        this.timeLimitMin = timeLimitMin;
        this.questions = new ArrayList<>(questions);
    }

    // Deep copy: the clone gets its own questions, so editing it never touches the template.
    Exam copy() {
        return new Exam(title, timeLimitMin, questions.stream().map(Question::copy).toList());
    }
}

public class Exams {
    public static void main(String[] args) {
        var srp = new Question("What does SRP stand for?", List.of("Single Responsibility", "Simple Routing"));
        Map<String, Exam> registry = Map.of("midterm", new Exam("Midterm", 45, List.of(srp)));

        Exam template = registry.get("midterm");
        Exam groupA = template.copy();
        groupA.title = "Midterm - group A";
        groupA.questions.get(0).options.add("Strict Rendering Pipeline");

        System.out.println(template.questions.get(0).options.size() + " vs "
            + groupA.questions.get(0).options.size());
    }
}
exams.go
package main

import "fmt"

type Question struct {
	Text    string
	Options []string
}

type Exam struct {
	Title        string
	TimeLimitMin int
	Questions    []Question
}

// Clone makes a deep copy. A plain assignment (b := a) copies the struct,
// but the Questions and Options slices would still be shared with the template.
func (e Exam) Clone() Exam {
	c := e
	c.Questions = make([]Question, len(e.Questions))
	for i, q := range e.Questions {
		q.Options = append([]string(nil), q.Options...)
		c.Questions[i] = q
	}
	return c
}

func main() {
	registry := map[string]Exam{
		"midterm": {
			Title:        "Midterm",
			TimeLimitMin: 45,
			Questions: []Question{
				{Text: "What does SRP stand for?", Options: []string{"Single Responsibility", "Simple Routing"}},
			},
		},
	}

	template := registry["midterm"]
	groupA := template.Clone()
	groupA.Title = "Midterm - group A"
	groupA.Questions[0].Text = "SRP means..."
	groupA.Questions[0].Options = append(groupA.Questions[0].Options, "Strict Rendering Pipeline")

	fmt.Println(template.Questions[0].Text, len(template.Questions[0].Options))
	fmt.Println(groupA.Questions[0].Text, len(groupA.Questions[0].Options))
}
exams.py
import copy
from dataclasses import dataclass, field, replace
from typing import Any, Self


@dataclass
class Question:
    text: str
    options: list[str] = field(default_factory=list)


@dataclass
class Exam:
    title: str
    time_limit_min: int
    questions: list[Question] = field(default_factory=list)

    def clone(self, **changes: Any) -> Self:
        # deepcopy gives the clone its own questions; replace() then applies the edits
        return replace(copy.deepcopy(self), **changes)


registry = {
    "midterm": Exam(
        "Midterm", 45, [Question("What does SRP stand for?", ["Single Responsibility", "Simple Routing"])]
    ),
}

if __name__ == "__main__":
    template = registry["midterm"]
    group_a = template.clone(title="Midterm - group A")
    group_a.questions[0].options.append("Strict Rendering Pipeline")
    print(len(template.questions[0].options), len(group_a.questions[0].options))  # 2 3

    shallow = replace(template, title="Shallow copy")  # replace() alone is shallow
    print("shares questions:", shallow.questions is template.questions)  # True

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • Step by step
  • When to use it and when not to
  • Related patterns
  • In practice
  • Quick check
  • Summary

Create a free account · Sign in