Creational Patternsmedium

Prototype Pattern

Create new objects by copying (cloning) an existing object, rather than constructing from scratch. Useful when construction is expensive or the type is unknown at compile time.

Memory anchor

Prototype = photocopying a document. Fast and cheap, but if the original has a sticky note (mutable reference), the copy just has a picture of it — you can't peel it off. Deep copy = rewriting the whole doc by hand, sticky notes included.

Expected depth

Prototype is appropriate when: (1) object initialization is costly (e.g., loading configuration from DB); (2) the system should be independent of how its products are created; (3) classes to instantiate are specified at runtime. Java implements this via Cloneable and clone(); most modern frameworks use copy constructors or serialization-based cloning. Shallow copy vs deep copy is the critical decision: shallow shares references (dangerous for mutable nested objects); deep duplicates the entire object graph.

Deep — senior internals

In Java, clone() is problematic: it is protected in Object, requires Cloneable (a marker interface with no methods), and the default behavior is a shallow copy — which silently shares mutable sub-objects. Effective Java recommends avoiding clone() in favor of copy constructors or static factory methods that accept the source object. Prototype is rarely used directly as a standalone pattern in modern code — it surfaces in object pool implementations (pre-warm a pool of clones), in undo/redo stacks (save state as a prototype snapshot), and in some serialization frameworks. The pattern is more common in JavaScript (prototypal inheritance is prototype at the language level).

🎤Interview-ready answer

Prototype is the pattern for cloning. I use it when constructing a fresh object is expensive — say, a report template that takes 500ms to build from raw data. I build it once, then clone it for each user session. The critical question is shallow vs deep copy. I use a copy constructor rather than clone() to control exactly what is deep-copied versus shared. In practice, I most often see prototype in undo/redo systems (each state is a clone of the previous) and in game engines (spawn an enemy from a template prototype).

Common trap

The shallow-vs-deep copy issue is where most prototype discussions break down. Shallow copy shares mutable sub-objects across clones — mutating one mutates all. Always specify whether your clone is shallow or deep, and justify why.

Related concepts