vendredi 24 avril 2020

How to clone an object created by a factory?

I was thinking about this problem and couldn't quite figure out what would be the most logical solution. I'll put forth the scenario of an interface/abstract class Animal, class Fish which inherits from Animal, and factory class AnimalFactory which instantiates Animal objects. I am tasked with cloning an instance of Fish. For reference, by 'clone' I mean using instance A to create a new instance B, where A != B, yet their classes and states are identical.

Now, my question is: how would you clone an instance of Fish? I guess what I'm wondering most here is, do you call the factory to clone it or not? Outlined below are the two most logical solutions I've come up with:

  • public clone() {/* return new fish with the same state */} in the Fish class.
  • public clone(Animal toClone) {/* return toClone.clone() */} in the AnimalFactory class, where clone() in the Fish class has protected access.

To reiterate my question: how would you clone an object created by a factory?

Aucun commentaire:

Enregistrer un commentaire