avoid instanceof in Java

前端 未结 9 2248
清歌不尽
清歌不尽 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

    The problem with instanceof is that you can suffer from future object hierarchy changes. The better approach is to use Strategy Pattern for the cases where you are likely to use instanceof. Making a solution with instanceof you are falling into a problem Strategy is trying to solve: to many ifs. Some guys have founded a community. Anti-IF Campaign could be a joke but untipattern is serious. In a long term projects maintaining 10-20 levels of if-else-if could be a pain. In your case you'd better make a common interface for all objects of your array and implement setUITweenManager for all of them through an interface.

    interface TweenManagerAware{
       setUITweenManager(UITweenManager manager);
    }
    

提交回复
热议问题