Files
design-patterns/01-creational/prototype

Prototype Design Pattern — Java Example

Pattern: Creational → Prototype Article: https://ankurm.com/prototype-design-pattern-java/

What this example shows

Documents cloned from existing instances instead of rebuilt from scratch. Copyable declares the cloning contract. DocumentMetadata is a nested object that must be copied correctly for a clone to be truly independent of its source. Document is the concrete prototype, implementing a real (not shallow) copy. DocumentRegistry stores a set of ready-made prototypes that callers clone on demand instead of constructing from raw parameters. Main demonstrates cloning from the registry and confirms the clone and original don't share mutable state.

How to run

javac prototype/*.java -d out/prototype
java -cp out/prototype prototype.Main

Requires Java 25.

Post Section ↔ File Mapping

Post Section File(s)
Part 1 — The Prototype Interface: Copyable Copyable.java
Part 2 — The Nested Object: DocumentMetadata DocumentMetadata.java
Part 3 — The Concrete Prototype: Document Document.java
Part 4 — The Prototype Registry: DocumentRegistry DocumentRegistry.java
Part 5 — Using the Prototype: Client Code Main.java

Note: the ShallowVsDeepDemo snippet (shallow vs. deep copy) and the Cloneable-based example are illustrative only — they are not part of this repository's runnable example.

Article: https://ankurm.com/prototype-design-pattern-java/ All patterns: https://ankurm.com/design-patterns-java/