我需要在
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 } } }
解决方法
如果您可以控制要复制的类,那么虚拟方法就是前进的方法:
class Foo { ... public Foo copy() { return new Foo(this); } } class Bar extends Foo { ... @Override public Bar copy() { return new Bar(this); } }
(理想情况下,使类成为抽象或有效的最终.)