我需要在
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 }
- }
- }