Prototype

GoF Definition

Specify the kinds of objects to create using a prototypical instance, and create new

objects by copying this prototype.

Prototype pattern allow you to create objects by cloning existing ones. The existing object is used as a template or prototype for building the new one. You can avoid the expense of creating a new instance using this concept.

Why do we need to clone objects? A few reasons are as follows:

  • To pass an object to some other module for processing, and you want to ensure that the original instance is not accidently tampered with in the process.

  • To perform some “preview” operations on an object. You just want to get a feel of how the object will be after the changes, but you don’t want to actually change the object.

  • The new object and an existing one might closely match each other. So, you can clone the first one, modify just a few properties that are different, and then use the new instance the way you want.

  • At times creating a new instance using the new keyword might add overhead to the object-creation process.

Take this example of cloning an uploaded file. Just in case if you want to create a back up of all uploaded files then this example holds good.

UploadedFile class implements interface IUploadedFile and it has to implement Clone() method.

This Clone method should create new object by copying all property values of "this" means itself.