从树中提取数据 [英] Extracting data from a tree
问题描述
T|||动物植物|||狗猫 ..
我有一个像上面这样的树结构,我需要解析它.我正在尝试设计一个 API,让人们阅读这棵树.我想通过让人们在这棵树中指定他们感兴趣的对象并返回它们来实现这一点.例如,如果我对猫感兴趣,我希望我的提取器方法返回所有猫.如果我想了解所有动物,我想返回所有动物对象.
我想我可以做这样的事情-
TreeDataExtractor 提取器 = new TreeExtractor();extractor.registerLivingThingOfInterest(LivingThings.ANIMAL);提取器.getData();
现在,这个方法 getData()
每次都会返回不同类型的对象.一次,它可以返回Plant
,另一次它可以返回Cat
.那么,我应该让它返回一个 LivingThing
吗?如果我让它返回一个超类类型,调用者是否应该在他的代码中应用强制转换?会不会有点丑?或者,我应该设计多个具有不同具体返回类型的方法 getCats()
, getAnimals()
吗?
您可以使用泛型使方法返回不同的类型.用户只需将类指定为参数,例如:
public T getData(Class clazz, Object otherParam) {//在这里插入代码}
你会像这样使用它:
Cat c = getData(Cat.class, otherParam);狗 d = getData(Dog.class, otherParam);
T | | | Animal Plant | | | Dog Cat ..
I have a tree structure like above, which I need to parse. I am trying to design an API that will let people read this tree. The way I want to accomplish this by letting people specify objects of their interest in this tree and return them. For instance, if I am interested in cats, I want my extractor method to return all cats. If I want to know about all animals, I want to return all animal objects.
I figured I can do something like this-
TreeDataExtractor extractor = new TreeExtractor();
extractor.registerLivingThingOfInterest(LivingThings.ANIMAL);
extractor.getData();
Now, this method getData()
will return different types of objects everytime. One time, it could return Plant
another time it could return Cat
. So, Should I just make it return a LivingThing
? If I make it return a superclass type, should the caller apply a cast in his code? Wouldn't it be a little ugly? Or, should I just design multiple methods getCats()
, getAnimals()
with different concrete return types?
You can use genericity to make the method return different types. The user will just have to specify the class as a parameter, for instance:
public <T extends LivingThing> T getData(Class<T> clazz, Object otherParam) {
// insert code here
}
And you would use it like this:
Cat c = getData(Cat.class, otherParam);
Dog d = getData(Dog.class, otherParam);
这篇关于从树中提取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!