Prototype

Also called: Smart Factory Method.

Problem

At runtime we need to create an object from its description.

Solution

The Prototype Pattern is like the factory method pattern. Instead of an abstract factory method a concrete factory method builds products based on product descriptions such as class names.

The basic idea is simple, although it sounds complicated. An abstract product base class maintains a static table that associates product descriptions with concrete product prototypes. The factory method merely searches the table for a prototype. It then asks the prototype to clone itself and returns the clone.

An interesting twist on the Prototype Pattern is that the roles of Abstract Product and Factory are often played by a single class.

Structure

Variations

Cloneable Products I in Java

A simple variation of the Prototype Pattern is worth mentioning. In this case the factory method always returns a clone of a single prototype. However, this prototype can be configured to point to various subclass instances:

A sample implementation can be found in:

PrototypeDemo.java

Cloneable Products II in Java

A complete Java implementation of the Prototype Pattern can be found in:

PrototypeDemo2.java

Using Reflection

Thanks to reflection, we don't need to rely on cloning prototypes in Java. If we can derive an instance of Java's Class representing the product subclass from the product description, then we can call the newInstance method to create the desired product. In many cases the product description is simply the name of the class, so we can write:

Class c = Class.forName(description);
AbstractProduct product = (AbstractProduct)c.newInstance();

A complete Java implementation can be found in:

PrototypeDemo3.java

Cloneable Products II in C++

The Prototype Pattern is important in C++ where there is a lack of support for reflection (RTTI just doesn't cut it.)

See The Prototype Pattern in C++ for a full discussion.

Types as Objects

The Prototype Pattern is closely related to the Types as Objects Pattern.