我需要在Java中克隆一个子类,但在代码的这一点上,我不知道子类的类型,只知道超类。有什么最好的设计模式可以做到这一点吗?
示例:
示例:
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 }
}
}
Bar.copy
重写了(使用@Override
检查)Foo.copy
。 - Tom Hawtin - tacklinecopy
的调用发生在运行时,JVM将根据对象的类型调用适当的copy
方法。 - Steve Kuo