Prototype
Purpose
Create a new object by copying a configured one. The pattern applies when the state that makes an object useful was assembled at runtime and is costly or undesirable to re-derive — a document template, a pre-wired processing pipeline, a scenario fixture — or when the copier does not know the concrete class it is duplicating.
In modern Java the pattern is often a warning. Immutable values usually can be shared, and
Java's built-in copying mechanism (Cloneable) has a weak contract. What survives should
normally use explicit copy constructors or copy factories; interoperability with a hierarchy
that already has a correct clone() contract is a constrained exception, not a reason to spread
that API.
Java 17 is the baseline for these partial examples; no preview features are required. Inspect compiler settings, copy APIs, persistence mappings/provider and ownership before applying them. Do not upgrade Java or persistence libraries merely to fit an example. Deliver the copy purpose, per-field ownership/identity policy, concurrency precondition and relevant validation or gaps.
When it is the answer
An object's configuration is assembled at runtime and duplicating it
is cheaper or more reliable than re-deriving it
→ Prototype, via a copy factory.
The set of things to instantiate is registered by name at runtime and
the registry does not know their classes
→ a registry of prototypes, each able to copy itself.
A mutable working object must be duplicated so two paths can diverge
(a scenario, a draft, a what-if calculation)
→ Prototype — and consider making the type immutable instead,
which may allow sharing when distinct identity/ownership is unnecessary.
When it is not
- The object is an immutable value and reference identity is irrelevant. Share the instance.
A distinct identity, lifecycle, ownership token, or native resource can still require a new
object even when exposed state is immutable (
java-immutability). - The state can be re-derived from parameters. Then a factory or builder is clearer, and the new object does not inherit whatever the source accumulated.
- Only polymorphic discovery is unnecessary. A known concrete type can use a copy constructor or named factory; that may still implement Prototype intent without a copy interface.
- Only a few fields differ from the original. Hand-written or generated
withXmethods can express "the same but for X" directly; Java records do not generate withers themselves. - The object is an entity with identity. Name whether this is a new entity or a snapshot; see the identity rules below before duplicating anything with an id, a version or a lifecycle.
Modern Java expression
Do not Do
────────────────────────────────── ─────────────────────────────────────
implements Cloneable a copy constructor:
Object clone() Config(Config other)
or a static copy factory:
static Config copyOf(Config other)
deep copy via serialise/deserialise an explicit copy that names each
field policy, with construction and
semantic tests for omissions
polymorphic clone() on a hierarchy an abstract copy() returning the
interface type, implemented per
subtype — a covariant, documented
contract you control
"copy then mutate two fields" record + withX(), or a builder seeded
from the original
Cloneable declares no copy method, Object.clone performs shallow field copying without constructor validation, and independently owned final mutable fields complicate repair of a super.clone result. These are limitations to audit, not proof that every clone implementation is invalid. Preserve a correct inherited contract when compatibility requires it; see references/copying-in-java.md.
Decision rules
IF the type is transitively immutable and identity/ownership permits sharing
THEN share the reference; distinct lifecycle or logical identity may still require a new object.
IF the copy shares any mutable substructure with the original
THEN classify the operation as shallow/selective/deep. Shared fields retain aliases;
decide whether that sharing is intended and compatible with ownership.
IF the graph contains cycles or object identity is meaningful
THEN a naive deep copy either loops forever or duplicates shared nodes.
Use a per-operation identity map keyed by the original node. Bound depth/nodes/work;
a visited map alone does not stop stack overflow on a deep acyclic chain.
IF the source can be mutated while it is being copied
THEN the copy can be internally inconsistent. Copy under the same lock
the mutators use, or snapshot into an immutable value first.
IF the object has persistent identity (@Id, a version, a natural key)
THEN first name the operation: clone-as-new-entity resets generated identity,
version and creation lifecycle; snapshot/copy-for-transfer may preserve identity.
Never pass a copied detached entity to persist/merge without defining semantics.
IF copying is done by serialising and deserialising
THEN account for format-specific cost, graph/identity semantics, transient or ignored
fields, constructors and compatibility. Native Java deserialization of untrusted
bytes can enable gadget attacks; not every serialization format has that failure mode.
IF a new field is added to the type
THEN tests or construction structure must expose an omitted copy policy. A constructor
call may fail to compile when its signature changes, but mutable classes and defaulted
components can still omit fields silently; use semantic copy-contract tests.
Cross-cutting checks
- Concurrency. Copying a mutable object is a multi-field read and is not atomic. Another
thread mutating the source mid-copy yields a "copy" that never existed — fields from before
and after the change. Either copy while holding whatever lock guards the source, or have the
source expose an immutable snapshot and copy that. A
copy()documented as thread-safe with no explanation of immutability, locking or snapshot publication is not evidence of safety (java-memory-model). - Distribution. Copying a DTO can preserve logical IDs and versions but does not duplicate the server entity or its lifecycle. Where a prototype is transmitted, the receiving process reconstructs it from bytes — which is deserialisation, with its own trust boundary, not this pattern. Never build a prototype registry keyed by class names supplied by a remote peer.
- Performance. "Copying is faster than constructing" is an assumption, not a fact: a deep
copy may traverse and allocate a large graph; escape analysis depends on the call context,
not the pattern name. Justify a prototype by the
configuration being expensive to reproduce, not by allocation cost — and if the claim is
about cost, measure it (
allocation-profiling). - Testing. A shared mutable prototype used as a test fixture is a cross-test dependency: one test mutating the copy's shared substructure changes another test's data. Prototype fixtures must be deep-copied, or be immutable, or be rebuilt per test.
Review checklist
- New code prefers an explicit constructor/factory; any retained
clone()contract is inherited, documented and tested across subtypes - Every field is accounted for: copied, deliberately shared, or deliberately reset
- Adding a field is caught by construction structure, generated code, or copy-contract tests
- Independently owned mutable containers and elements are copied; intentional sharing is explicit
- Identity, version, lifecycle and correlation fields follow an explicit clone-as-new versus snapshot/transfer policy
- Copying under concurrency is either locked or performed on an immutable snapshot
- Any retained serialization copy has a justified format, graph, trust and resource contract
- Immutable values are shared when identity and ownership permit it
References
- Copying in Java — Cloneable limitations and compatibility, copy constructors against copy factories against wither methods, the deep-versus-shallow decision table, cycles and identity maps, the serialisation round-trip's costs and security surface, and the rules for copying JPA entities. Read before implementing any copy.
- Worked example — a registry of configured document templates instantiated per request: the Cloneable version and its ownership risks, the copy-factory version, identity reset when the copy is persisted, and the snapshot that makes copying safe under concurrency. Read when implementing.