I was going through the Prototype design pattern and had some questions.
I have understood the Prototype design pattern is used for the creation of objects that are costly in terms of memory or resources. In that case we use a clone of the object which is already available.
So what is the difference between creating a new
object and clone()
? Where is the object stored in memory?
Prototype design pattern offers costs savings of two kinds - time savings and space savings.
Time savings come in situations when creating an object requires a costly access to auxiliary information - say, requesting configuration data from a file, a database, or over a network. For example, if you are building lots of pages from a template that is stored on a web server, it is cheaper to read the template once and clone it to get the starting point for each new page, rather than querying the web server separately for each page.
Memory savings come from reusing immutable objects: if your original contains lots of strings, creating a new instance would need to either create entirely new immutable strings, or deal with string interning manually. Using the prototype pattern gracefully avoids this problem by letting the clone share the immutable parts of the template.