Prototype is another creation pattern.
- Specify the kinds of objects to create using a prototypical instance
In college, we have all done this, one friend downloads the assignment from college online portal and its gets distributed using pen-drive. Probably a close example!? ;)
It does not however exactly the prototype pattern, since it does not returns a cloned object, but sounds pretty close. :)
Please share your story of implementing Prototype in comments. Will be helpful to people learning it for the first time. :)
Intent:
- Intent is to create objects by cloning existing instance- Specify the kinds of objects to create using a prototypical instance
Why cloning?
Sometimes, we run into situation where object creation is expensive, specially when it involves network I/O or interacting with database etc. How do we allow object creation, without doing lots of rigorous gymnastics, for objects similar in nature? Prototype design pattern comes handy here. Objects are cloned with some initial setup that requires little or no further changes.In college, we have all done this, one friend downloads the assignment from college online portal and its gets distributed using pen-drive. Probably a close example!? ;)
But, can you give some real world examples?
- cloning set of agreements from a archive store, and adding contact details later. (That's the exactly what real state agents do, misspelling you names or id details, and ask you to verify. :P )
- cloning a job with other instance members - only difference is ID and executionTime.
- creating test dummies!?
- Creating a new case/user story, by cloning ServiceNow case, or JIRA or Trello!! :)
A little side story
I came across the term prototype while learning about Spring Bean scopes, one of them is prototype.It does not however exactly the prototype pattern, since it does not returns a cloned object, but sounds pretty close. :)
Ok, How does it look like?
Source:Wikipedia |
Can I have a look at a Pseudo-code?
You can find it on this wiki page.Anything else I should know?
- Yes, you need to aware of your clone implementation. In java, default behavior is shallow copy, field by field copy, where primitives are copied as new values, and members of class types are copied as reference, hence both the cloned object and actual object points to the same objects. So, be aware of this fact, while choosing/writing clone method implantation.
- And, also classes needs to implement Cloneable interface and override clone method. Note that Cloneable is a marker interface, so it does not explicitly contains clone method. Read more on official java document here.
- It may appear to overlap with AbstractFactory pattern, but its a bit different in the sense, it does not require subclassing, rather it relies on an initialization method (eventually relies on clone).
Please share your story of implementing Prototype in comments. Will be helpful to people learning it for the first time. :)
No comments:
Post a Comment