简体   繁体   English

使用镜像类层次结构转换对象的设计

[英]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 我有一个低级 (即不能依赖于高级模块)MySQL DAO包,该包返回多态对象

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). 我正在尝试在此使用者包中编写一个适配器,该适配器需要使用MySQL DAO检索MySQLCat对象,并以抽象类的形式返回它(即,实现retrieveAllAnimals(...)方法)。 What would be the cleanest way (read: without having to call instanceof ) to do this? 什么是最干净的方法(阅读:无需调用instanceof )?

Have a HashMap from Class to Class . ClassClass有一个HashMap 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. 当一个对象进入时,从它自己的类中在HashMap中查找它,然后实例化新类的对象,并使用反射来复制相同名称的所有成员变量。

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());

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

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