This pattern is used when the creation of object directly is costly. Prototype Pattern says that cloning of an existing object instead of creating a new one and can also be customized according to requirements.
Client - creates a new object by asking a prototype to clone itself.
Prototype - declares an interface for cloning itself.
ConcretePrototype - implements the operation for cloning itself.
This is the sample code for prototype pattern
It can be used to replicate the Session from one server to another server.
It can be used to generate the GUI having many numbers of similar controls.
Advantage of Prototype Pattern
Reduced load of initialization
If we create many objects of the same class by calling the constructor and then initialize every property for each object explicitly. We need to write the repetitive lines of code to initialize every property for every object created. It may increase the time complexity if there are costly operations involved. We can reduce the initializations cost using prototype pattern as we can create the object by cloning of the existing object. The object created by the clone method reflects the same state of the original object.
Simplified object copy process
It hides complexities of creating objects as it creates the deep copy complex object hierarchy. Object copying is done recursively by calling the Clone method on every member composition object, this makes the program structure easier to understand and maintain.
Reusability - Optimized coding efforts
An object created in the system and initialized with the default/non-default properties is sufficient to create the similar object copies. There are few properties which can vary from one object to another object; we need for those properties and need not write the code to initialize the objects again and again. This will optimize the coding efforts of writing the code to initialize the properties that are different between objects of the same class or structure.
Prototype Design Pattern helps in reducing the number of classes.
When there are many subclasses that differ only in the kind of objects they create. Prototype Pattern can be used to reduce the number of subclasses by cloning a prototype.