简体   繁体   English

当仅知道其抽象基类时如何复制对象

[英]How to copy an object when only its abstract base class is known

I have an abstract base class MusicTime , which has several concrete subclasses - Quaver , SemiQuaver , Crotchet etc. The subclass instances are contained in a List<? extends MusicTime> 我有一个抽象基类MusicTime ,它具有几个具体的子类QuaverSemiQuaverCrotchet等。这些子类实例包含在List<? extends MusicTime> List<? extends MusicTime> collection. List<? extends MusicTime>集合。

I need to be able to clone these objects, and am doing this manually by iterating through the collection and creating new instances based on the existing instance. 我需要能够克隆这些对象,并通过遍历集合并基于现有实例创建新实例来手动执行此操作。 I obviously can't instantiate an abstract class, so is there any way of calling the constructor of the same MusicTime constructor as each existing instance? 我显然不能实例化一个抽象类,那么有什么方法可以调用与每个现有实例相同的MusicTime构造函数的构造函数? So if it's a Quaver then I create a new Quaver object? 因此,如果它是Quaver那么我将创建一个新的Quaver对象?

I see a clean and a dirty solution: 我看到一个干净又肮脏的解决方案:

  • implement the clone() (from the Cloneable interface) method for each of the classes in the hierarchy (clean solution) 为层次结构中的每个类(干净的解决方案)实现clone() (从Cloneable接口)方法
  • use instanceof operator to find out which class is the object instance of (dirty solution) 使用instanceof运算符找出哪个类是(肮脏的解决方案)的对象实例

  • I believe you can use Prototype design pattern, with that you can add 我相信您可以使用Prototype设计模式,并添加

    abstract MusicTime clone()
    

    in your MusicTime base class, and implement in all the subclasses which create its own object. 在您的MusicTime基类中,并在所有创建其自己的对象的子类中实现。 When you iterate through list call clone. 当您遍历列表调用克隆时。

    http://www.codeproject.com/Articles/42582/Prototype-Design-Pattern http://www.codeproject.com/Articles/42582/Prototype-Design-Pattern

    http://java.dzone.com/articles/design-patterns-prototype http://java.dzone.com/articles/design-patterns-prototype

    声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM