Design patterns

patterns5PrototypePattern

Path
pkg8patterns/patterns5PrototypePattern.java
Package
pkg8patterns
Study order
5
Run
Single-file source launch
Command
java pkg8patterns/patterns5PrototypePattern.java

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg8patterns/patterns5PrototypePattern.java
1package pkg8patterns;2 3/*4 * Prototype (Creational)5 * ----------------------6 * INTENT: create new objects by copying an existing instance (the prototype),7 *         instead of instantiating from scratch.8 * UML: Prototype + clone(): Prototype ; concrete prototypes implement copy.9 * PROS: cheap creation of complex objects; avoids subclassing factories.10 * CONS: deep vs shallow copy is tricky for nested mutable state.11 * REAL-WORLD: Object.clone(), copying configured templates.12 */13import java.util.*;14 15public class patterns5PrototypePattern {16 17    static class Document implements Cloneable {18        String title;19        List<String> sections;     // mutable -> needs deep copy20 21        Document(String title, List<String> sections) {22            this.title = title;23            this.sections = sections;24        }25 26        // Deep copy so clones don't share the sections list27        @Override public Document clone() {28            return new Document(this.title, new ArrayList<>(this.sections));29        }30        @Override public String toString() { return title + " " + sections; }31    }32 33    public static void main(String[] args) {34        Document original = new Document("Template", new ArrayList<>(List.of("Intro", "Body")));35        Document copy = original.clone();36        copy.title = "Copy";37        copy.sections.add("Conclusion");      // does NOT affect original (deep copy)38 39        System.out.println("original: " + original);40        System.out.println("copy:     " + copy);41        System.out.println("independent lists? " + (original.sections != copy.sections));42    }43}