Codacoda
Back to Academy

design patterns

Prototype

The Prototype pattern creates new objects by cloning an existing object (the prototype) rather than creating from scratch. It avoids the cost of creating objects the standard way (using 'new') when it is more expensive or complex. The key participants are the Prototype (declares a cloning interface), ConcretePrototype (implements the cloning operation), and Client (creates a new object by asking a prototype to clone itself). Think of cell division in biology: a cell creates a copy of itself rather than being assembled from scratch molecule by molecule. Use Prototype when creating an object is expensive (database lookups, complex initialization) and a similar object already exists, or when you want to avoid building a class hierarchy of factories that mirrors the product hierarchy.

Use Cases

  • Cloning complex configuration or state objects
  • Creating objects with expensive initialization (e.g., parsing files)
  • Implementing undo/redo by snapshotting object state
  • Spawning game entities from pre-configured templates

Visualization

clone()<<interface>>Prototype+clone()ConcretePrototypeA+clone()fieldAConcretePrototypeB+clone()fieldBClientoperation()
Speed:1x
Prototype — creates new objects by cloning an existing instanceStep 1 / 6

Implementation

Output

Click "Run Code" to see output...