我需要在Java中克隆一个子类,但是在代码中发生这种情况的那一点上,我将不知道子类的类型,只知道父类(super class)。最佳的设计模式是什么?
例子:
class Foo {
String myFoo;
public Foo(){}
public Foo(Foo old) {
this.myFoo = old.myFoo;
}
}
class Bar extends Foo {
String myBar;
public Bar(){}
public Bar(Bar old) {
super(old); // copies myFoo
this.myBar = old.myBar;
}
}
class Copier {
Foo foo;
public Foo makeCopy(Foo oldFoo) {
// this doesn't work if oldFoo is actually an
// instance of Bar, because myBar is not copied
Foo newFoo = new Foo(oldFoo);
return newFoo;
// unfortunately, I can't predict what oldFoo's the actual class
// is, so I can't go:
// if (oldFoo instanceof Bar) { // copy Bar here }
}
}
最佳答案
如果您可以控制要复制的类,则可以使用虚拟方法:
class Foo {
...
public Foo copy() {
return new Foo(this);
}
}
class Bar extends Foo {
...
@Override public Bar copy() {
return new Bar(this);
}
}
(理想情况下,使类成为抽象类或使类最终成为类。)
关于java - 克隆Java中的子类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4329141/