I need to copy an object with a rather deep hierarchy of member variables (i.e. the object has several members of different types, each of which has several members of different types, etc.). A deep copy will require the implementation of the clone () method in many classes, which seems redundant for my application.
The solution I came up with is pretty simple, but I wonder, a bad idea. My solution is this:
- Determine the blank interface
Settings. - Define an interface with a name
IsCopyablethat has methods getSettings()and applySettings(Settings s). - For a given class
Xthat implements IsCopyable, a class is written that implements an interface Settingsthat contains the “settings” that must be applied to the class object Xin order to copy it, (I usually insert this class into the class X, so I have one X.Settings implements Settings, but it can be done in another location.)
Then, to copy an instance of class X:
X myX = new X();
X copyOfX = new X();
copyOfX.applySettings(myX.getSettings());
Ie, to copy this object, create a new instance of this object, then call it getSettings()on the object you want to copy, passing the resulting object Settingsas a value applySettings()to the new instance. (Of course, copying can be wrapped in a member called copy () or something like that.)
, - ? () , ?
.