Prototype

So, you’ve got a complicated object to build and you’ve been using an Expert Builder to make it, but now you realise you need multiple copies of these objects. You may no longer have access to the builder after construction. It happens. The builder may not be code you control. Either way, you want lots of these complicated objects and using the builder whenever you need a new one adds overhead.

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 Prototype and keep it pristine. Use it only as a template to generate more when needed.

You can also use Prototypes when the class to construct needs to change at runtime. Furthermore, if the instances share read-only data, cloning can reduce the cost because it’s often quicker to identify and reuse read-only references rather than having different mechanisms for constructing different parts of objects. The clone operation only needs to duplicate the mutable state.

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.”