栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

这里的instanceof检查有什么问题吗?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

这里的instanceof检查有什么问题吗?

您可以使用双重调用。无可否认,这是一个更好的解决方案,但这是另一种选择。

代码示例

import java.util.HashMap;public class Example {    public static void main(String[] argv) {        Example ex = new Example();        ICacheable[] cacheableObjects = new ICacheable[]{new MyObject(), new OtherObject()};        for (ICacheable iCacheable : cacheableObjects) { // depending on whether the object is a MyObject or an OtherObject, // the .put(Example) method will double dispatch to either // the put(MyObject) or  put(OtherObject) method, below iCacheable.put(ex);        }        System.out.println("myObjects: "+ex.myObjects.size());        System.out.println("otherObjects: "+ex.otherObjects.size());    }    private HashMap<String, MyObject> myObjects = new HashMap<String, MyObject>();    private HashMap<String, OtherObject> otherObjects = new HashMap<String, OtherObject>();    public Example() {    }    public void put(MyObject myObject) {        myObjects.put(myObject.getKey(), myObject);    }    public void put(OtherObject otherObject) {        otherObjects.put(otherObject.getKey(), otherObject);    }}interface ICacheable {    public String getKey();    public void put(Example ex);}class MyObject implements ICacheable {    public String getKey() {        return "MyObject"+this.hashCode();    }    public void put(Example ex) {        ex.put(this);    }}class OtherObject implements ICacheable {    public String getKey() {       return "OtherObject"+this.hashCode();    }    public void put(Example ex) {        ex.put(this);    }}

这里的想法是-
而不是强制转换或使用

instanceof
-而是调用
iCacheable
对象的
.put(...)
方法,该方法将自身传递回
Example
对象的重载方法。调用哪种方法取决于该对象的类型。

另请参阅“
访客”模式。我的代码示例

ICacheable.put(...)
发出了臭味,因为该方法具有内聚力-
但使用Visitor模式中定义的接口可以清除该异味。

为什么我不能直接
this.put(iCacheable)
Example
班级打来电话?

在Java中,重载总是在运行时绑定的,但是重载则稍微复杂一些:动态调度意味着将在运行时选择方法的实现,但是方法的签名仍然是在编译时确定的。(有关更多信息,请查看Java语言规范的第8.4.9章,还请参阅Java
Puzzlers一书的第137页的益智游戏“为其制作哈希” 。)



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/610190.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号