用Java克隆子类
发布时间:2020-12-14 05:55:04 所属栏目:Java 来源:网络整理
导读:我需要在 Java中克隆一个子类,但是在代码发生这种情况时,我不会知道子类类型,只知道超类.这样做的最佳设计模式是什么? 例: class Foo { String myFoo; public Foo(){} public Foo(Foo old) { this.myFoo = old.myFoo; }}class Bar extends Foo { String my
我需要在
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); } } (理想情况下,使类成为抽象或有效的最终.) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |