What is the Prototype pattern and how does it work?

The Prototype pattern is a creational pattern that creates new objects by cloning an existing prototype instance rather than instantiating a class from scratch. It's useful when object creation is expensive or complex.

Key Points: • A prototype object exposes a clone() method that returns a copy of itself. • Cloning can be shallow, copying field values directly, or deep, copying referenced objects too. • It avoids repeating expensive initialization logic, such as loading data or expensive computation, for every new instance. • New objects can be created without knowing the exact concrete class, since the client just clones an existing instance. • Prototypes are often stored in a registry so client code can request a clone by key.

Example: In a game, instead of re-running the initialization logic for an Enemy object every time one spawns, the game can clone a pre-configured prototype Enemy and just tweak its position, which is far cheaper than constructing it from scratch each time.

Interview Tip: A concise interview answer is:

"Prototype creates new objects by cloning an existing instance instead of building one from scratch, which is valuable when construction is expensive. In Java it's typically implemented with the Cloneable interface and an overridden clone() method, choosing shallow or deep copying depending on whether referenced objects need to be independent."