{"id":"6b08bd3c80884893657cc9f1","slug":"prototype","title":"Prototype – a new object as a copy of a ready-made template","summary":"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.","servedLang":"en","availableLangs":["pl","en"],"topics":["prototype","abstract-factory","memento"],"techs":["dotnet","typescript","java","go","python"],"tags":["gof","creational","prototype","cloning","deep-copy"],"level":"intermediate","kind":"article","access":"members","status":"published","cover":null,"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"readingMinutes":10,"stats":{"views":3,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-26T23:14:04.737Z","updatedAt":"2026-11-27T13:04:32.155Z","requestedLang":"en","theme":{"hero":"classic","heroMedia":null,"accent":"green","background":"dots","weaveResources":true,"toc":"right"},"seoDescription":"The Prototype design pattern – cloning objects, shallow vs deep copy, a prototype registry, code in C#, TypeScript, Java, Go and Python, the pitfalls of Cloneable, structuredClone and copy.deepcopy.","wordCount":1950,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Sometimes the easiest way to create an object is to take a similar one and change a few details. "},{"type":"text","text":"Prototype","marks":[{"type":"bold"}]},{"type":"text","text":" 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."}]},{"type":"callout","attrs":{"variant":"info","title":"In short"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"The object exposes a "},{"type":"text","text":"clone()","marks":[{"type":"code"}]},{"type":"text","text":" method that returns an independent copy of itself."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"You keep ready-made, configured instances (prototypes) in a registry and clone them on demand."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"The key decision is the depth of the copy: a shallow copy shares nested objects with the original."}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"the-problem-an-exam-for-group-b"},"content":[{"type":"text","text":"The problem: an exam for group B"}]},{"type":"paragraph","content":[{"type":"text","text":"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:"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"duplicate-exam.ts"},"content":[{"type":"text","text":"function duplicate(exam: Exam): Exam {\n  // copies the fields, but the questions array is the same object!\n  return { ...exam, title: exam.title + \" (copy)\" };\n}\n\nconst groupB = duplicate(midterm);\ngroupB.questions[3].options.push(\"None of the above\"); // midterm changes too"}]},{"type":"paragraph","content":[{"type":"text","text":"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."}]},{"type":"heading","attrs":{"level":2,"id":"the-solution-an-object-that-can-clone-itself"},"content":[{"type":"text","text":"The solution: an object that can clone itself"}]},{"type":"paragraph","content":[{"type":"text","text":"We move the responsibility for copying into the object itself. "},{"type":"text","text":"Exam.clone()","marks":[{"type":"code"}]},{"type":"text","text":" 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."}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"classDiagram\n  direction LR\n  class Prototype~T~ {\n    <<interface>>\n    +clone() T\n  }\n  class Exam {\n    +title\n    +timeLimit\n    +questions\n    +clone() Exam\n  }\n  class Question {\n    +text\n    +options\n    +clone() Question\n  }\n  class TemplateRegistry {\n    +get(name) Exam\n  }\n  Prototype <|.. Exam\n  Prototype <|.. Question\n  Exam *-- Question\n  TemplateRegistry o-- Exam : prototypes","caption":"Prototype with a template registry"}},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Role"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"In the example"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Responsibility"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Prototype"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"IPrototype<T>","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"declares the cloning operation"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Concrete prototype"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Exam","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Question","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"implements the copy and decides its depth"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Registry (optional)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"a dictionary of templates"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"stores configured prototypes by name"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Client"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the \"Duplicate exam\" view"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"asks for a copy without knowing construction details"}]}]}]}]},{"type":"section","attrs":{"background":"dots","width":"wide","padding":"m"},"content":[{"type":"heading","attrs":{"level":2,"id":"shallow-or-deep-copy"},"content":[{"type":"text","text":"Shallow or deep copy?"}]},{"type":"paragraph","content":[{"type":"text","text":"This is the heart of the pattern. A "},{"type":"text","text":"shallow copy","marks":[{"type":"bold"}]},{"type":"text","text":" creates a new object, but fields that point to other objects still point to the same instances. A "},{"type":"text","text":"deep copy","marks":[{"type":"bold"}]},{"type":"text","text":" recursively copies nested objects as well. Immutable fields – strings, numbers, records without setters – can be shared safely; collections and mutable objects must be cloned."}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"flowchart LR\n  subgraph P[\"Shallow copy\"]\n    A1[\"Template\"] --> L1[(\"Question list\")]\n    B1[\"Copy\"] --> L1\n  end\n  subgraph G[\"Deep copy\"]\n    A2[\"Template\"] --> L2[(\"Question list\")]\n    B2[\"Copy\"] --> L3[(\"Its own question list\")]\n  end","caption":"A shallow copy shares the question list, a deep copy has its own"}}]},{"type":"heading","attrs":{"level":2,"id":"implementation-in-five-languages"},"content":[{"type":"text","text":"Implementation in five languages"}]},{"type":"paragraph","content":[{"type":"text","text":"Each language has its traps here: a C# record with "},{"type":"text","text":"with","marks":[{"type":"code"}]},{"type":"text","text":" and Python's "},{"type":"text","text":"dataclasses.replace()","marks":[{"type":"code"}]},{"type":"text","text":" 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."}]},{"type":"codeGroup","attrs":{"title":"Exam.Clone()"},"content":[{"type":"codeBlock","attrs":{"language":"csharp","filename":"Exams.cs"},"content":[{"type":"text","text":"var registry = new Dictionary<string, Exam>\n{\n    [\"midterm\"] = new Exam(\"Midterm\", TimeSpan.FromMinutes(45),\n        [new Question(\"What does SRP stand for?\", [\"Single Responsibility\", \"Simple Routing\"])]),\n};\n\nvar groupA = registry[\"midterm\"].Clone();\ngroupA.Title = \"Midterm - group A\";\ngroupA.Questions[0].Options.Add(\"Strict Rendering Pipeline\");\n\nvar template = registry[\"midterm\"];\nConsole.WriteLine($\"{template.Questions[0].Options.Count} vs {groupA.Questions[0].Options.Count}\");\n\npublic interface IPrototype<out T>\n{\n    T Clone();\n}\n\npublic sealed class Question(string text, List<string> options) : IPrototype<Question>\n{\n    public string Text { get; set; } = text;\n    public List<string> Options { get; } = options;\n\n    public Question Clone() => new(Text, [.. Options]);\n}\n\npublic sealed class Exam(string title, TimeSpan timeLimit, List<Question> questions)\n    : IPrototype<Exam>\n{\n    public string Title { get; set; } = title;\n    public TimeSpan TimeLimit { get; set; } = timeLimit;\n    public List<Question> Questions { get; } = questions;\n\n    // Deep copy: the clone gets its own questions, so editing it never touches the template.\n    public Exam Clone() => new(Title, TimeLimit, Questions.Select(q => q.Clone()).ToList());\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"exams.ts"},"content":[{"type":"text","text":"class Question {\n  constructor(public text: string, public readonly options: string[]) {}\n\n  clone(): Question {\n    return new Question(this.text, [...this.options]);\n  }\n}\n\nclass Exam {\n  constructor(\n    public title: string,\n    public timeLimitMin: number,\n    public readonly questions: Question[],\n  ) {}\n\n  // Deep copy: the clone gets its own questions, so editing it never touches the template.\n  clone(): Exam {\n    return new Exam(this.title, this.timeLimitMin, this.questions.map((q) => q.clone()));\n  }\n}\n\nconst registry = new Map<string, Exam>([\n  [\n    \"midterm\",\n    new Exam(\"Midterm\", 45, [\n      new Question(\"What does SRP stand for?\", [\"Single Responsibility\", \"Simple Routing\"]),\n    ]),\n  ],\n]);\n\nconst template = registry.get(\"midterm\")!;\nconst groupA = template.clone();\ngroupA.title = \"Midterm - group A\";\ngroupA.questions[0].options.push(\"Strict Rendering Pipeline\");\nconsole.log(template.questions[0].options.length, groupA.questions[0].options.length); // 2 3"}]},{"type":"codeBlock","attrs":{"language":"java","filename":"Exams.java"},"content":[{"type":"text","text":"import java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\n\nfinal class Question {\n    String text;\n    final List<String> options;\n\n    Question(String text, List<String> options) {\n        this.text = text;\n        this.options = new ArrayList<>(options);\n    }\n\n    // Copy constructors/methods are the idiomatic Java alternative to Cloneable.\n    Question copy() { return new Question(text, options); }\n}\n\nfinal class Exam {\n    String title;\n    int timeLimitMin;\n    final List<Question> questions;\n\n    Exam(String title, int timeLimitMin, List<Question> questions) {\n        this.title = title;\n        this.timeLimitMin = timeLimitMin;\n        this.questions = new ArrayList<>(questions);\n    }\n\n    // Deep copy: the clone gets its own questions, so editing it never touches the template.\n    Exam copy() {\n        return new Exam(title, timeLimitMin, questions.stream().map(Question::copy).toList());\n    }\n}\n\npublic class Exams {\n    public static void main(String[] args) {\n        var srp = new Question(\"What does SRP stand for?\", List.of(\"Single Responsibility\", \"Simple Routing\"));\n        Map<String, Exam> registry = Map.of(\"midterm\", new Exam(\"Midterm\", 45, List.of(srp)));\n\n        Exam template = registry.get(\"midterm\");\n        Exam groupA = template.copy();\n        groupA.title = \"Midterm - group A\";\n        groupA.questions.get(0).options.add(\"Strict Rendering Pipeline\");\n\n        System.out.println(template.questions.get(0).options.size() + \" vs \"\n            + groupA.questions.get(0).options.size());\n    }\n}"}]},{"type":"codeBlock","attrs":{"language":"go","filename":"exams.go"},"content":[{"type":"text","text":"package main\n\nimport \"fmt\"\n\ntype Question struct {\n\tText    string\n\tOptions []string\n}\n\ntype Exam struct {\n\tTitle        string\n\tTimeLimitMin int\n\tQuestions    []Question\n}\n\n// Clone makes a deep copy. A plain assignment (b := a) copies the struct,\n// but the Questions and Options slices would still be shared with the template.\nfunc (e Exam) Clone() Exam {\n\tc := e\n\tc.Questions = make([]Question, len(e.Questions))\n\tfor i, q := range e.Questions {\n\t\tq.Options = append([]string(nil), q.Options...)\n\t\tc.Questions[i] = q\n\t}\n\treturn c\n}\n\nfunc main() {\n\tregistry := map[string]Exam{\n\t\t\"midterm\": {\n\t\t\tTitle:        \"Midterm\",\n\t\t\tTimeLimitMin: 45,\n\t\t\tQuestions: []Question{\n\t\t\t\t{Text: \"What does SRP stand for?\", Options: []string{\"Single Responsibility\", \"Simple Routing\"}},\n\t\t\t},\n\t\t},\n\t}\n\n\ttemplate := registry[\"midterm\"]\n\tgroupA := template.Clone()\n\tgroupA.Title = \"Midterm - group A\"\n\tgroupA.Questions[0].Text = \"SRP means...\"\n\tgroupA.Questions[0].Options = append(groupA.Questions[0].Options, \"Strict Rendering Pipeline\")\n\n\tfmt.Println(template.Questions[0].Text, len(template.Questions[0].Options))\n\tfmt.Println(groupA.Questions[0].Text, len(groupA.Questions[0].Options))\n}"}]},{"type":"codeBlock","attrs":{"language":"python","filename":"exams.py"},"content":[{"type":"text","text":"import copy\nfrom dataclasses import dataclass, field, replace\nfrom typing import Any, Self\n\n\n@dataclass\nclass Question:\n    text: str\n    options: list[str] = field(default_factory=list)\n\n\n@dataclass\nclass Exam:\n    title: str\n    time_limit_min: int\n    questions: list[Question] = field(default_factory=list)\n\n    def clone(self, **changes: Any) -> Self:\n        # deepcopy gives the clone its own questions; replace() then applies the edits\n        return replace(copy.deepcopy(self), **changes)\n\n\nregistry = {\n    \"midterm\": Exam(\n        \"Midterm\", 45, [Question(\"What does SRP stand for?\", [\"Single Responsibility\", \"Simple Routing\"])]\n    ),\n}\n\nif __name__ == \"__main__\":\n    template = registry[\"midterm\"]\n    group_a = template.clone(title=\"Midterm - group A\")\n    group_a.questions[0].options.append(\"Strict Rendering Pipeline\")\n    print(len(template.questions[0].options), len(group_a.questions[0].options))  # 2 3\n\n    shallow = replace(template, title=\"Shallow copy\")  # replace() alone is shallow\n    print(\"shares questions:\", shallow.questions is template.questions)  # True"}]}]}]},"toc":[{"id":"the-problem-an-exam-for-group-b","text":"The problem: an exam for group B","level":2,"locked":false},{"id":"the-solution-an-object-that-can-clone-itself","text":"The solution: an object that can clone itself","level":2,"locked":false},{"id":"shallow-or-deep-copy","text":"Shallow or deep copy?","level":2,"locked":false},{"id":"implementation-in-five-languages","text":"Implementation in five languages","level":2,"locked":false},{"id":"step-by-step","text":"Step by step","level":2,"locked":true},{"id":"when-to-use-it-and-when-not-to","text":"When to use it and when not to","level":2,"locked":true},{"id":"related-patterns","text":"Related patterns","level":2,"locked":true},{"id":"in-practice","text":"In practice","level":2,"locked":true},{"id":"quick-check","text":"Quick check","level":2,"locked":true},{"id":"summary","text":"Summary","level":2,"locked":true}],"locked":true,"paywall":null,"previewRatio":0.3,"totalBlocks":34,"visibleBlocks":14,"resources":[{"id":"6b0857bf3c96f2d34d0b42d8","type":"article","provider":"web","url":"https://gameprogrammingpatterns.com/prototype.html","embedUrl":null,"title":"Prototype · Design Patterns Revisited · Game Programming Patterns","description":"","author":"Robert Nystrom","thumbnailUrl":null,"durationSec":null,"lang":"en","topics":["prototype"],"techs":["general"],"tags":["design-patterns"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":60,"verifiedAt":"2026-11-26T11:26:37.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:02.417Z","updatedAt":"2026-11-26T23:13:50.482Z"},{"id":"6b0857bf3c96f2d34d0b4242","type":"article","provider":"web","url":"https://refactoring.guru/design-patterns/prototype","embedUrl":null,"title":"Prototype","description":"Prototype is a creational design pattern that lets you copy existing objects without making your code dependent on their classes.","author":"Refactoring.Guru","thumbnailUrl":"https://refactoring.guru/images/refactoring/social/facebook-share-preview.png?id=dbf9e98269595be86eb668f365be6868","durationSec":null,"lang":"en","topics":["prototype"],"techs":["general"],"tags":["design-patterns"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":70,"verifiedAt":"2026-11-26T11:26:00.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:02.417Z","updatedAt":"2026-11-26T16:01:02.417Z"},{"id":"6b0857c33c96f2d34d0b4665","type":"book","provider":"openlibrary","url":"https://openlibrary.org/works/OL6223299W","embedUrl":null,"title":"Effective Java","description":"","author":"Joshua Bloch","thumbnailUrl":"https://covers.openlibrary.org/b/id/1176573-L.jpg","durationSec":null,"lang":"en","topics":[],"techs":["java"],"tags":["book"],"price":"paid","featured":false,"featuredOrder":0,"packageName":null,"source":"openlibrary","publishedAt":"2001-01-01T00:00:00.000Z","popularity":62,"verifiedAt":"2026-11-26T11:00:08.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:04.995Z","updatedAt":"2026-11-26T16:01:04.995Z"},{"id":"6b0857c33c96f2d34d0b4658","type":"book","provider":"openlibrary","url":"https://openlibrary.org/works/OL6030812W","embedUrl":null,"title":"Design Patterns: Elements of Reusable Object-Oriented Software","description":"","author":"Erich Gamma, John Vlissides, Richard Helm, Ralph Johnson","thumbnailUrl":"https://covers.openlibrary.org/b/id/6601119-L.jpg","durationSec":null,"lang":"en","topics":["factory-method","abstract-factory","builder","prototype","singleton","adapter","bridge","composite","decorator","facade","flyweight","proxy","chain-of-responsibility","command","iterator","mediator","memento","observer","state","strategy","template-method","visitor"],"techs":["general"],"tags":["book","design-patterns"],"price":"paid","featured":false,"featuredOrder":0,"packageName":null,"source":"openlibrary","publishedAt":"1995-01-01T00:00:00.000Z","popularity":71,"verifiedAt":"2026-11-26T11:00:08.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:04.995Z","updatedAt":"2026-11-26T16:01:04.995Z"}],"challenges":[{"id":"6b093ddfbd4755deb67ee09b","slug":"serialize-binary-tree","title":"Serialize a binary tree","summary":"Write a binary tree to a string and rebuild it – with empty subtrees, negative numbers and trees thousands of levels deep. Format design, BFS and the recursion trap.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":"algorithms","status":"published","difficulty":"hard","topics":["memento"],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["trees","binary-tree","bfs","dfs","serialization","design"],"languages":["typescript","javascript","python","csharp","java","go"],"questionCount":null,"xp":40,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:55.586Z"},{"id":"6b093dc191bd8fbaf2a0c8c8","slug":"game-checkpoint-memento","title":"Game checkpoints","summary":"Saving and restoring a hero's state with Memento – immutable snapshots without shared lists, a caretaker with limited capacity and protection against loading someone else's save.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":"pattern","status":"published","difficulty":"easy","topics":["memento"],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["memento","snapshots","undo","immutability","behavioral"],"languages":["typescript","javascript","python","csharp","java","go"],"questionCount":null,"xp":10,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:25.224Z"}],"attachments":[],"hasCode":true,"repoUrl":null,"series":[{"slug":"gof-creational","title":"GoF creational patterns","items":[{"slug":"factory-method","title":"Factory Method – let the subclass decide what gets created","current":false},{"slug":"abstract-factory","title":"Abstract Factory – whole families of objects that fit together","current":false},{"slug":"builder","title":"Builder – complex objects step by step","current":false},{"slug":"prototype","title":"Prototype – a new object as a copy of a ready-made template","current":true},{"slug":"singleton","title":"Singleton – one instance, and the reasons to hand it to a DI container","current":false}]}],"prev":{"slug":"builder","title":"Builder – complex objects step by step"},"next":{"slug":"singleton","title":"Singleton – one instance, and the reasons to hand it to a DI container"},"featured":false,"authorCard":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","headline":"Wzorce projektowe · Architektura · AI i LLM","community":false,"reputation":{"points":3900,"level":{"key":"mentor","label":"Mentor"}},"articles":68,"skills":[{"key":"typescript","title":"TypeScript","level":5,"levelLabel":"Authority","articles":63},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Authority","articles":53},{"key":"python","title":"Python","level":5,"levelLabel":"Authority","articles":52},{"key":"java","title":"Java","level":5,"levelLabel":"Authority","articles":38}]}}