如何在不使用instanceof的情况下找到类型? [英] How to find type without using instanceof?

查看:82
本文介绍了如何在不使用instanceof的情况下找到类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的类 Query 中有一个接口类型为 Criteria List .

I have a List of interface type Criteria within my class Query.

List<Criteria> criteria = new ArrayList<Criteria>();

我有 Criteria 的几种具体实现.我想给 Query 提供一个遍历 criteria 列表的方法,并根据具体类型执行一些逻辑.

I have several concrete implementations of Criteria. I want to give Query a method that iterates through my criteria list, and depending on the concrete type, execute some logic.

我目前正在使用 instanceof 这样,

for(Criteria c : criteria) {
    if(c instanceof ContextualCriteria){
        // logic
    }
    ...
}

这是唯一/最好的方法吗?

Is this the only/best way?

推荐答案

逻辑是否合理地属于 Criteria 本身?如果是这样,请将其放入 Criteria 接口,并为实现 Criteria 接口的每个具体类适当地实现它.显然,这是 nice 多态方法.

Does the logic sensibly belong in the Criteria itself? If so, put it into the Criteria interface and implement it appropriately for each concrete class implementing the Criteria interface. This is obviously the nice polymorphic approach.

不幸的是,在现实生活中,OO并非总是那么简单-有时将按类型的行为放入类型本身是没有意义的,因此您可能需要使用 instanceof 代替.您可以潜在地从条件类"到某个表示要执行的操作的接口的映射,但这很容易最终变得更加混乱.

Unfortunately, in real life OO doesn't always work as simply as that - sometimes it doesn't make sense to put the per-type behaviour in the type itself, so you may need to use instanceof instead. You could potentially have a map from "criteria class" to some interface representing the action to take, but that could easily end up being even messier.

通过访问者模式进行两次调度有时可以改善一点点-因此逻辑仍然可以在调用"类中的单独方法中,但是每个 Criteria 都可以通过单个接口方法将 back 调用到正确的方法.我个人倾向于发现这种耦合会增加耦合并很快变得丑陋,但其他人对此发誓.

Double-dispatch via the visitor pattern can sometimes improve things a little - so the logic could still be in separate methods in your "calling" class, but each Criteria can call back to the right method via a single interface method. Personally I tend to find this increases coupling and gets ugly quickly, but others swear by it.

这篇关于如何在不使用instanceof的情况下找到类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆