您可以使用双重调用。无可否认,这是一个更好的解决方案,但这是另一种选择。
代码示例
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页的益智游戏“为其制作哈希” 。)



