Artykuł · Prototyp · Fabryka abstrakcyjna
Prototyp (Prototype) – nowy obiekt jako kopia gotowego wzorca
Prototyp tworzy obiekty przez klonowanie skonfigurowanego egzemplarza zamiast budowania ich od zera. Wyjaśniamy różnicę między kopią płytką a głęboką na przykładzie szablonów egzaminów.
Czasem najprościej utworzyć obiekt, biorąc podobny i zmieniając kilka szczegółów. Prototyp (ang. Prototype) robi z tego wzorzec: obiekt sam umie się skopiować, a kod, który potrzebuje nowego egzemplarza, nie musi znać jego klasy ani wszystkich parametrów konfiguracji.
Problem: egzamin dla grupy B
Na platformie kursów programowania prowadzący przygotowuje egzamin: tytuł, limit czasu, kilkadziesiąt pytań, każde z listą odpowiedzi, ustawienia losowania kolejności. Dla grupy B chce tego samego egzaminu z dwiema zmienionymi odpowiedziami. Pierwsza wersja funkcji „Duplikuj” wyglądała tak:
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 tooOperator rozwinięcia (spread) kopiuje tylko pierwszy poziom. Lista pytań jest współdzielona, więc edycja wersji dla grupy B po cichu zmienia egzamin grupy A – błąd wychodzi na jaw dopiero, gdy studenci widzą odpowiedź, której nie powinno tam być. Drugi problem: kod duplikujący musi znać wszystkie pola egzaminu i aktualizować się przy każdej zmianie klasy.
Rozwiązanie: obiekt, który umie się sklonować
Odpowiedzialność za kopiowanie przenosimy do samego obiektu. Exam.clone() wie, które pola można skopiować wprost (tytuł, limit czasu), a które trzeba sklonować rekurencyjnie (pytania, a w nich listy odpowiedzi). Gotowe szablony – „kolokwium”, „egzamin końcowy”, „quiz na rozgrzewkę” – trzymamy w rejestrze i klonujemy, zamiast budować od zera.
| Rola | W przykładzie | Odpowiedzialność |
|---|---|---|
| Prototyp (Prototype) | IPrototype<T> | deklaruje operację klonowania |
| Prototyp konkretny | Exam, Question | implementuje kopię, decydując o jej głębokości |
| Rejestr (opcjonalny) | słownik szablonów | przechowuje skonfigurowane prototypy pod nazwami |
| Klient | widok „Duplikuj egzamin” | prosi o kopię, nie znając szczegółów konstrukcji |
Płytka czy głęboka kopia?
To serce wzorca. Kopia płytka (shallow copy) tworzy nowy obiekt, ale pola wskazujące na inne obiekty nadal wskazują na te same egzemplarze. Kopia głęboka (deep copy) rekurencyjnie kopiuje również obiekty zagnieżdżone. Pola niezmienne – napisy, liczby, rekordy bez setterów – można bezpiecznie współdzielić; kolekcje i obiekty zmienne trzeba sklonować.
Implementacja w pięciu językach
Każdy język ma tu swoje pułapki: rekord w C# z with i dataclasses.replace() w Pythonie robią kopię płytką, operator rozwinięcia w TypeScripcie także, a w Go przypisanie struktury kopiuje ją, ale wycinki (slices) dalej wskazują na tę samą tablicę. Dlatego każda implementacja klonuje kolekcje jawnie.
Exam.Clone()
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());
}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 3import 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());
}
}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))
}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) # TrueDalsza część artykułu dla zalogowanych
Załóż darmowe konto albo zaloguj się, aby przeczytać całość. W dalszej części:
- Krok po kroku
- Kiedy stosować, a kiedy nie
- Powiązania z innymi wzorcami
- W praktyce
- Szybki test
- Podsumowanie