简体   繁体   中英

Design for converting objects with mirroring class hierarchy

I have a low-level (ie cannot depend on higher-level modules) MySQL DAO package that returns polymorphic objects

abstract class MySQLAnimal {
    int a;
}

class MySQLCat extends MySQLAnimal {
    int b;
}

Collection<MySQLAnimal> retrieveAllMySQLAnimals(...) {...}

Then, I have a consumer of this package that provides abstraction (ie it's agnostic of how they are retrieved) and contains classes with mirroring class hierarchy:

abstract class Animal {
    int a;
}

class Cat extends Animal {
    int b;
}

Collection<Animal> retrieveAllAnimals(...) {...}

I'm trying to write an adapter in this consumer package that needs to retrieve MySQLCat object using MySQL DAO and return it in the form of abstracted class (ie implementing the retrieveAllAnimals(...) method). What would be the cleanest way (read: without having to call instanceof ) to do this?

Have a HashMap from Class to Class . When an object comes in look it up in the HashMap from it's own class then instantiate an object of the new class and use reflection to copy all member variables of the same name.

The only change needed to support new classes in the future is adding new mappings, which could be stored in a config file.

ie

mapping.put(MySQLCat.class, Cat.class);

Class<? extends Animal> targetClass = mapping.get(objectToMap.getClass());

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