Prototype
So, you’ve got a complicated object to build and you’ve been using an
The other time this becomes necessary is when you are working inside a document and hoping to copy-paste a dynamically constructed object into another position. In this case, you wish to clone a live editable object.
Instead of building each new object, you can create by cloning. Take the first
object as a
You can also use
Cloning is applicable even when a deep copy is required if loading data or calculating values for construction are expensive or greater than the cost to clone.
In languages without reflection, the base class will need to expose a clone method. You must override it for any necessary exceptional cases; otherwise, it will do what it says and return a unique copy of the object.
Recurring issues with prototypes generally revolve around identity. Usually, objects are created, live their life, and then die. But with a prototype, some actions will have happened on the original object, which have now also occurred in the past for the clone. They share a history before the point of cloning. Cloning mistakes can lead to shared unique IDs. Objects can become subscribed to more than one publisher when you clone the publisher or a clone might think they are subscribed when they are not. Anything where the object’s identity is relevant becomes a potential source of error.
“So, you want more of these? Okay, I shall make usable copies for you.”