The prototype pattern is used to produce a duplicate or clone of an existing object in order to improve speed. This pattern is used when the production of an object is expensive or complicated.
Example of Prototype Pattern
An object will be created after a costly database operation. We can cache the object, return its clone on subsequent requests, and update the database as needed, hence decreasing database calls.
When to use the Prototype pattern?
The prototype pattern is useful in the following scenarios:
The creation of each object is costly or complex.
A limited number of state combinations exist in an object.
Prototype Design pattern with UML diagram
Object Cloning
Object cloning in C# creates a new object with the same values as an existing one.
Types of Object Cloning
There are 2 types of Object Cloning:
Shallow Copy
Deep Copy
Shallow Copy
Only the top-level objects are duplicated or copied. A shallow copy generates a new object by copying the current object's non-static fields into the new object.
Deep Copy
All objects are duplicates or copies. A shallow copy generates a new object by copying the existing object's non-static fields.
Advantages of the Prototype Pattern
Avoids Expensive Creation: It is useful when developing an object is more expensive or complicated than copying an existing one.
Encapsulates complexity: The prototype encapsulates the complexity and details of object creation.
Adds and Removes Objects: Objects can be added and removed during runtime.
Specifying New Objects: Clients can create new objects by changing values from a prototype.
Reducing Subclassing: The pattern eliminates the requirement for subclasses.