avoid instanceof in Java

前端 未结 9 2261
清歌不尽
清歌不尽 2021-02-12 20:40

I have been told at some stage at university (and have subsequently read in upteen places) that using instanceof should only be used as a \'last resort\'. With this

9条回答
  •  情歌与酒
    2021-02-12 21:13

    It is always a bit "fishy" to me to mix objects of different classes in the same Collection. Would it be possible / make sense to split the single Collection of GameObjects into multiple Collections, one of mere GameObjects, another of UITweenables? (e.g. use a MultiMap keyed by a Class). Then you could go something like:

    for (UITweenable uit : myMap.get(UITweenable.class)) {
      uit.setUITweenManager(mUITweenManager);
    }
    

    Now, you still need an instanceof when you insert into the map, but it's better encapsulated - hidden from the client code who doesn't need to know those details

    p.s. I'm not a fanatic about all the SW "rules", but Google "Liskov Substitution Principle".

提交回复
热议问题