> For the complete documentation index, see [llms.txt](https://khaled-hamam.gitbook.io/design-patterns-explained/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://khaled-hamam.gitbook.io/design-patterns-explained/library/creational-patterns/prototype.md).

# Prototype Pattern

## Intent

Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype instead of depending on the **new** operator.

## When to use

1. When the object instantiation from the beginning takes a lot of time.
2. When we want to specify an instance of the class to use it as a breeder of all future instances.
3. To avoid building a class hierarchy (seperate classes or factories) that parallels the class hierarchy of the products.
4. If we want to instantiate the same class with a minimal change of state, it's more appropriate to clone the instance and change its state to the required state.

## Structure

![](https://2149973296-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MKKrm5lFe01Ro4BXbPp%2Fsync%2F75610286b0d6017f670202c62ab7c4e2ee9a6b93.png?generation=1603463578535513\&alt=media)

* Prototype: defines the interface for cloning
* ConcretePrototype: implements the operation for cloning itself.
* Client: creates a new object by asking a prototype to clone itself.
* Registry: **optional** class that saves the frequently used prototypes, either before compilation, or even in runtime.

## Examples

|                                                                            Source Code                                                                           |   UML   |
| :--------------------------------------------------------------------------------------------------------------------------------------------------------------: | :-----: |
| [Example 1](https://github.com/khaled-hamam/ts-design-patterns/tree/369ec4e91fe87ca563f4d94388bceb028fa467bd/library/creational-patterns/prototype/example_1.ts) | // TODO |
| [Example 2](https://github.com/khaled-hamam/ts-design-patterns/tree/369ec4e91fe87ca563f4d94388bceb028fa467bd/library/creational-patterns/prototype/example_2.ts) | // TODO |

You can find the tests [here](https://github.com/khaled-hamam/ts-design-patterns/tree/369ec4e91fe87ca563f4d94388bceb028fa467bd/library/creational-patterns/prototype/index.test.ts).
