JavaScript language implements this design pattern. The entire language itself. Everything you use in JavaScript is a clone.
When to Use:
- When construction is expensive/take long time to process;
- State is important. You want to copy states before it leaves off;
- When you want to hide the constructor.
Participants
Class/Interface | Description |
---|---|
Prototype | Interface or Abstract Class. It defines a method to clone an object |
ConcretePrototype1, ConcretePrototype2 | A class that implements the Prototype. It has a method to copy itself. Deep or shallow copy. |
Client | Consumes the Prototype |
Sample Implementation
In this example, we are going to create a prototype that detects even numbers from 1 to N. A delay was included to assume that the process is expensive. Then we are going to clone the result.
UML Class Diagram for Even Number Generator
Mapping
Prototype Design Pattern | Even Number Generator |
---|---|
Prototype | IEvenNumberGen.cs |
ConcretePrototype | EvenNumbersGenerator.cs |
Client | Program.cs |
The Codes
IEvenNumberGen.cs
EvenNumbersGenerator.cs
Program.cs
The Output
If you you compare the original and the clone, the original processed the data and clone did not. It just copied the object.
I hope this is helpful. Drop some comments.