When to do Object Cloning in Java – a sample scenario !!

Posted: June 2, 2013 in Uncategorized
Tags: , , , , , ,

I was getting trained on design patterns and this question came into my mind when we were discussing about ‘Prototype Design Pattern’ – when should I used object cloning in java ?

Finally after a bit of google search, i found a satisfactory answer or scenario where it can be of great help.

Quite often you want to use immutable objects, in which case cloning is an essential part of your code. If for example you have an immutable object that has a list or array type field, your getter should always return a clone of the list or array to preserve immutability.

The other typical use case is when you want “transactional” modifications, when you call several state changing methods but only want the result to be visible if all of them are successful.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s