Prototype

creational

Specifies the kinds of objects to create using a prototypal instance, and creates new objects by copying this prototype.

Intent

The Prototype pattern specifies the kinds of objects to create using a prototypal instance, and creates new objects by copying this prototype.

Motivation

When the classes to instantiate are specified at runtime, or to avoid building a class hierarchy of factories that parallels the class hierarchy of products, or when instances of a class can have one of only a few different combinations of state, the Prototype pattern is useful.

Structure

The pattern declares a cloning interface in all classes that support cloning. Usually it's a single clone method. Concrete prototype classes implement the cloning method.

Participants

  • Prototype - declares an interface for cloning itself
  • ConcretePrototype - implements an operation for cloning itself
  • Client - creates a new object by asking a prototype to clone itself

Pros

  • Clones objects without coupling to their concrete classes
  • Eliminates repeated initialization code
  • Produces complex objects more conveniently
  • Alternative to inheritance for handling presets

Cons

  • Cloning complex objects with circular references can be tricky
  • Deep copy can be expensive

Use Cases

Creating objects from a database
Cloning game objects
Copying configuration objects
Creating object templates

Implementation Tips

Considerations

  • Decide on shallow vs deep copy
  • Consider using a prototype registry
  • Handle circular references carefully

Tips

  • Use the clone() method to create copies
  • Consider using Object.assign() or spread operator for shallow copies
  • For deep copies, use structuredClone() or custom logic
  • Be careful with objects containing methods

Interactive Code Editor