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 is a creational design pattern that allows cloning objects, even complex ones, without coupling to their specific classes. All prototype classes should have a common interface that makes it possible to copy objects even if their concrete classes are unknown.
The prototype pattern is a creational design pattern. Prototype patterns are required, when object creation is time consuming, and costly operation, so we create objects with the existing object itself.
Applying the pattern lets you clone complex structures instead of re-constructing them from scratch. Prototype isn't based on inheritance, so it doesn't have its drawbacks. On the other hand, Prototype requires a complicated initialization of the cloned object.
The Java clone()
method just creates a new object and copies member variable values into it. In general, it's neither more nor less expensive than creating a new object. The only time clone()
might be cheaper than creating an object with new
would be when the constructor for an object does something expensive: for example, what if the constructor took the arguments and used them as part of a database query? In that case, using clone()
would be cheaper, as the expensive query operation would not happen.
There are other reasons to use this design pattern though: mostly, when objects need complicated setup before use which can't be conveniently done in a constructor. Imagine that an object had 20 properties that needed to be set. If you set them with constructor parameters, that constructor would be horribly ugly -- imagine a constructor with 20 parameters! Instead, you could construct an object with perhaps no parameters, set the 20 values using mutator methods, then clone()
the object to make ready-made copies when needed. clone()
needs no parameters at all, so it's obviously less ugly. If you needed multiple copies of several different versions of this object, then the prototype pattern becomes attractive.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With