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
Prototypeobjects:
-
To act as a prototype,
an object
must implement the
Prototypeinterface (clone()) for copying itself. -
For example, a
Product1object that implements theclone()operation can act as a prototype for creatingProduct1objects.
-
To act as a prototype,
an object
must implement the
-
Create new objects by copying a
Prototypeobject
(Product product = prototype.clone()).
-
This enables run-time flexibility (via object composition).
A class can be configured with differentPrototypeobjects, which are copied to create new objects, and even more,Prototypeobjects can be added and removed dynamically 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?
-
How can objects be created
-
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.