Search code examples
oopdesign-patternscopyprototypeclone

Clone function for prototype design pattern?


One of the most important parts of the prototype design pattern in OOP is that we don't create new objects from scratch, we just clone them using the clone() function from an existing object.

So is the clone() function a deep or shallow copy?

If it's a deep copy, than I understand everything, but if it's shallow one, it will be mess if two different objects (one created from another using a prototype pattern) watch same state objects, than it means that these object aren't different at all (they are linked as they share same state objects).

Can anyone clarify this situation to me?


Solution

  • Java Object clone method implements Prototype design pattern. A new instance is created using the prototypical instance. But the clone just gives you a shallow copy, it is not a deep copy. So it is rather a dangerous copy. If you need a deep copy, you have to explicitly implement it. The clone copies primitive values, but not object references. So both the original and the clone will point to the same object references, and if one modifies the same is applied to the other, leaving your objects in a dangerous state.