简体   繁体   中英

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> List<? extends MusicTime> collection.

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? So if it's a Quaver then I create a new Quaver object?

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)
  • use instanceof operator to find out which class is the object instance of (dirty solution)

  • I believe you can use Prototype design pattern, with that you can add

    abstract MusicTime clone()
    

    in your MusicTime base class, and implement in all the subclasses which create its own object. When you iterate through list call clone.

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

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

    The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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