Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat are some good design patterns for copying an object?
    text
    copied!<p>I need to copy an object that has a pretty deep hierarchy of member variables (i.e., the object has several members of various types, each of which has several members of various types, etc.). Doing a deep copy would require implementing a clone() method in many classes, which seems overkill for my application.</p> <p>The solution I've come up with is fairly simple, but I wonder if it's a bad idea. My solution is as follows:</p> <ul> <li>Define an empty interface, <code>Settings</code>.</li> <li>Define an interface called <code>IsCopyable</code>, which has methods <code>getSettings()</code> and <code>applySettings(Settings s)</code>.</li> <li>For a given class <code>X</code> that implements <code>IsCopyable</code>, a class that implements the interface <code>Settings</code> is written that holds the 'settings' that must be applied to an object of class <code>X</code> in order to copy it. (I usually nest this class within the class <code>X</code>, so I have <code>X.Settings implements Settings</code>, but this could be done elsewhere.)</li> </ul> <p>Then, to copy an instance of class X:</p> <pre><code>X myX = new X(); // Stuff happens to myX. // Now we want to copy myX. X copyOfX = new X(); copyOfX.applySettings(myX.getSettings()); </code></pre> <p>I.e., to copy a given object, create a new instance of that object, then call <code>getSettings()</code> on the object to be copied, passing the resulting <code>Settings</code> object as a value to <code>applySettings()</code> on the new instance. (Of course, the copying could be wrapped in a member called copy() or something.)</p> <p>This works very well for my particular problem, but am I doing something stupid? Have I (poorly) reinvented something that already exists?</p> <p>Thanks in advance.</p> <p>Chris</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload