The Prototype pattern allows an object to create customized objects without knowing their exact class or the details of how to create them.It specifies the kinds of objects to create using a prototypical instance, and creates new objects by copying this prototype. The Prototype pattern works by giving prototypical objects to an object and then initiates the creation of objects. The creation-initiating object then creates objects by asking the prototypical objects to make copies of themselves.
The Prototype pattern makes creating objects dynamically easier by defining classes whose objects can duplicate themselves.
The following lists the benefits of using the Prototype pattern:
Adding and removing products at run time.
Specifying new objects by varying values.
Specifying new objects by varying structure
Configuring an application with classes dynamically
When To Use the Prototype Pattern:
The classes to instantiate are specified at run time, for example, by dynamic loading.
To avoid building a class hierarchy of factories that parallels the class hierarchy of products
When instances of a class can have one of only a few different combinations of state
The prototype pattern is a creational design pattern used in software development when the type of objects to create
is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used to:
avoid subclasses of an object creator in the client application, like the abstract factory pattern does.
avoid the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword) when it
is prohibitively expensive for a given application.
To implement the pattern, declare an abstract base class that specifies a pure virtual clone() method.
Any class that needs a "polymorphic constructor" capability derives itself from the abstract base class, and implements the clone() operation.
The client, instead of writing code that invokes the "new" operator on a hard-coded class name,
calls the clone() method on the prototype, calls a factory method with a parameter designating the particular concrete derived class desired, or invokes the clone() method through
some mechanism provided by another design pattern.