Prototype

Prototype

Intent

Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.

Applicability

Use the prototype pattern when:

  • A system should be independent of how it's products are created, composed, and represented.
  • When the classes to instantiate are specified at run-time, e.g. dynamic loading.
  • To avoid building a class hierarchy of factories that parallels the class hierarchy of products.
  • When isntances of a class can have one of only a few different combinations of state.

Structure

Orange

Participants

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

Collaborations

A client asks a prototype to clone itself.

Consequences

Prototype has mant of the same consequences that Abstract Factory and Builder have: it hides the concrete product classes from client, thereby reducing the number of names clients know about. Moreover, these patterns let a client work with application-specific classes without modification. Additional benefits include:

  • Adding and removing products at run-time.
  • Specifying new objects by varying values.
  • Specifying new objects by varying structure.
  • Reduced subclassing
  • Configuring an application with classes dynamically.

Sample Code

Prototype

Related Patterns

  • Prototype and Abstract Factory are competing patterns in some way.
  • Designs that make heavy use of the Composite and Decorator patterns often can benefit from Prototype as well.