What is the Prototype pattern?

Topic: design-patterns, Creational Patterns. Level: Intermediate.

Answer

Prototype creates new objects by **cloning an existing instance** (the prototype) instead of instantiating from scratch. It's useful when object creation is expensive (heavy initialization, DB/network load) or when you need many similar objects — you configure one and copy it. Key concern: **deep vs shallow copy** (nested mutable references must be deep-copied to avoid shared-state bugs). In Java you can implement `Cleanable`/`clone()` or a copy constructor. ```java interface Prototype<T> { T copy(); } class Document implements Prototype<Document> { private String title; private List<String> sections; // mutable -> must deep copy Document(String t, List<String> s){ title=t; sections=s; } public Document copy() { return new Document(title, new ArrayList<>(sections)); // DEEP copy } } Document template = new Document("Report", List.of("Intro")); Document copy = template.copy(); // cheap clone instead of rebuilding from scratch ```