avoid instanceof in Java

前端 未结 9 2257
清歌不尽
清歌不尽 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 20:48

    I learned about Visitor pattern in Compiler class at university, I think it might apply in your scenario. Consider code below:

    public class GameObjectVisitor {
    
        public boolean visit(GameObject1 obj1) { return true; }
        .
        .
        // one method for each game object
        public boolean visit(GameGroup obj1) { return true; }
    }
    

    And then you can put a method in GameObject interface like this:

    public interface GameObject {
    
        .
        .
        public boolean visit(GameObjectVisitor visitor);
    }
    

    And then each GameObject implements this method:

    public class GameGroup implements GameObject {
    
        .
        .
        .
        public boolean visit(GameObjectVisitor visitor) {
            visitor.visit(this);
        }
    }
    

    This is specially useful when you've complex inheritance hierarchy of GameObject. For your case your method will look like this:

    private void allocateUITweenManager() {
    
        GameObjectVisitor gameGroupVisitor = new GameObjectVisitor() {
            public boolean visit(GameGroup obj1) {
                obj1.setUITweenManager(mUITweenManager);
            }
        };
    
        for(GameObject go:mGameObjects){
          go.visit(gameGroupVisitor);
       }
    }
    

提交回复
热议问题