Prototype Pattern

# Prototype

- Purpose
- Structure
- Applications
- Consequences

## Purpose

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

## Structure

- Prototype(Graphic): declares an interface for cloning itself.
- ConcretePrototype(Staff, WholeNote, HalfNote): implements an operation for cloning itself.
- Client(GraphicTool): creates a new object by asking a prototype to clone itself.

## Applications

- when 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. It may be more convenient to install a corresponding number of prototypes and clone them rather than instantiating the class manually, each time with the appropriate state.

## Consequences

- Adding and removing products at run-time. Prototypes let you incorporate a new concrete product class into a system simply by registering a prototypical instance with the client. That's a bit more flexible than other creational patterns, because a client can install and remove prototypes at run-time.
- Specifying new objects by varying values. Highly dynamic systems let you define new behavior through object composition—by specifying values for an object's variables, for example—and not by defining new classes. You effectively define new kinds of objects by instantiating existing classes and registering the instances as prototypes of client objects. A client can exhibit new behavior by delegating responsibility to the prototype.
- Specifying new objects by varying structure. Many applications build objects from parts and subparts. Editors for circuit design, for example, build circuits out of subcircuits. For convenience, such applications often let you instantiate complex, user-defined structures, say, to use a specific subcircuit again and again.The Prototype pattern supports this as well. We simply add this subcircuit as a prototype to the palette of available circuit elements. As long as the composite circuit object implements Clone as a deep copy, circuits with different structures can be prototypes.
- Configuring an application with classes dynamically. Some run-time environments let you load classes into an application dynamically. The Prototype pattern is the key to exploiting such facilities in a language like C++.