Questions tagged «chain-of-responsibility»

8
避免在Java中使用instanceof
具有“ instanceof”操作链被认为是“代码异味”。标准答案是“使用多态性”。在这种情况下我该怎么办? 有许多基类的子类。他们都不在我的控制之下。类似的情况是Java类Integer,Double,BigDecimal等。 if (obj instanceof Integer) {NumberStuff.handle((Integer)obj);} else if (obj instanceof BigDecimal) {BigDecimalStuff.handle((BigDecimal)obj);} else if (obj instanceof Double) {DoubleStuff.handle((Double)obj);} 我确实可以控制NumberStuff等。 我不想使用几行代码就能完成的代码。(有时,我制作了一个HashMap将Integer.class映射到IntegerStuff的实例,将BigDecimal.class映射到BigDecimalStuff的实例,等等。但是今天我想要一些更简单的方法。) 我想要这样简单的东西: public static handle(Integer num) { ... } public static handle(BigDecimal num) { ... } 但是Java不能那样工作。 我想在格式化时使用静态方法。我正在格式化的东西是复合的,其中Thing1可以包含Thing2s数组,Thing2可以包含Thing1s数组。当实现这样的格式化程序时,我遇到了一个问题: class Thing1Formatter { private static Thing2Formatter thing2Formatter = new Thing2Formatter(); public …

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.