The 23 GoF design patterns and Dependency Injection – choose a pattern Abstract Factory design patternBuilder design patternFactory Method design patternPrototype design patternSingleton design patternAdapter design patternBridge design patternComposite design patternDecorator design patternFacade design patternFlyweight design patternProxy design patternChain of Responsibility design patternCommand design patternInterpreter design patternIterator design patternMediator design patternMemento design patternObserver design patternState design patternStrategy design patternTemplate Method design patternVisitor design patternDependency Injection design pattern

Prototype Design Pattern

Creational pattern. Creational design patterns are concerned with object creation.

The Prototype design pattern solves problems like: How can objects be created so that which objects to create can be specified at run-time?

Open in the interactive referenceDownload the PDF reference

Solution

The Prototype design pattern provides a solution:
Define a Prototype object that returns a copy of itself.
Create new objects by copying a Prototype object.
Describing the Prototype design in more detail is the theme of the following sections.
See Applicability section for all problems Prototype can solve.

  • The key idea in this pattern is to create new objects by copying existing objects.
  • Define Prototype objects:
    • To act as a prototype, an object must implement the Prototype interface (clone()) for copying itself.
    • For example, a Product1 object that implements the clone() operation can act as a prototype for creating Product1 objects.
  • Create new objects by copying a Prototype object
    (Product product = prototype.clone()).
  • This enables run-time flexibility (via object composition).
    A class can be configured with different Prototype objects, which are copied to create new objects, and even more, Prototype objects can be added and removed dynami­cally at run-time.

Applicability

Design Problems

  • Creating Objects
    • How can objects be created
      so that which objects to create can be specified at run-time?
  • Instantiating Dynamically Loaded Classes
    • How can dynamically loaded classes be instantiated?

Not included on this page: Intent, Problem, Motivation, Structure, Consequences, Implementation, Related Patterns. See the GoF Design Patterns Reference (PDF) for the complete description.