Prototype Pattern
When we want the type of an object to be determined by a prototypical instance, we use Prototype pattern to clone the instance to create a new object that we extend as per our new needs. (wiki)
Sometimes in our application, we may want to take an existing object (lets call this objectOriginal), and create another object, lets say objectCloned, by making an exact copy of, or in other words, cloning the ‘objectOriginal’ as it is in its current state and then start working on this objectCloned, having its own autonomicity , so that an operation on objectCloned, like setting a new value to one of its properties, doesn’t affect the objectOriginal.
Instead of creating the objectCloned using new keyword on its class, and then setting all its properties to bring it to the same state as of ‘objectOriginal’, we may implement Prototype pattern so that we can clone the ‘objectOriginal’ by just calling some method like ‘cloneMe’.
var objectCloned = objectOriginal.cloneMe();
This would also save resources and cost that otherwise would have been needed had we used ‘new’ keyword to create objectCloned.
Imagine those Game console app, that allow user to configure his/her ‘avatar’.
In step 1, it asks user to select a body type based on the user’s gender. Lets say at this point the user’s avatar object is stored in userAvatar_Step1.
In step 2, it asks user to select a hair-style. Lets say user selects ‘curly’ hair style. At this point we may set the ‘userAvatar_Step1’ object’s hairstyle property to ‘curly’. Or alternatively, we can clone ‘userAvatar_Step1’ object to create ‘userAvatar_Step2’ and then set userAvatar_Step2’s hairstyle property to ‘curly’.
In cloning, we are preserving the userAvatar_Step1 object as is, so that at any point user does an ‘undo’, we can simply go back to ‘userAvatar_Step1’ and dispose ‘userAvatar_Step2’ (or cache in case user wants to ‘redo’). Also, like said before, cloning saves us resources, time and cost that otherwise would have been needed if we had used ‘new’ keyword to create ‘userAvatar_Step2’.
|
Again, this resource and this youtube video can help you better understand Prototype pattern.
