オブジェクトのディープ コピーをポリモーフィックに作成する方法の可能性をネットで検索しているときに、フィールドを複製できないなど、この方法に関する多くの問題を解決すると主張する解決策を見つけました。ソリューションは、実装内で保護されたコピー コンストラクターの使用を組み合わせ、基本的には次のようになります (参照ページからコピーされた例)。clone()
final
clone()
public class Person implements Cloneable
{
private final Brain brain; // brain is final since I do not want
// any transplant on it once created!
private int age;
public Person(Brain aBrain, int theAge)
{
brain = aBrain;
age = theAge;
}
protected Person(Person another)
{
Brain refBrain = null;
try
{
refBrain = (Brain) another.brain.clone();
// You can set the brain in the constructor
}
catch(CloneNotSupportedException e) {}
brain = refBrain;
age = another.age;
}
public Object clone()
{
return new Person(this);
}
…
}
のclone()
方法はBrain
、同様の方法で実施することができる。
メソッドのドキュメントにclone()
基づくと、このメソッドのすべての「コントラクト」は「絶対的な要件ではなく」、「返されたオブジェクトは を呼び出すことによって取得する必要がある」というsuper.clone()
のは単なる慣例のようです。
では、この実装は実際には正しくないのでしょうか? なんで?
もしそれが正しいなら、なぜデザインパターンにならなかったのですか?これの欠点は何ですか?
ありがとう、ペトル