Java: using polymorphism to avoid if-statements?

前端 未结 9 729
执念已碎
执念已碎 2020-12-29 08:30

I\'m attempting to write a java program that initializes certain layouts based on what the user selects. What I want to do is try to avoid writing a bunch of if-statements s

9条回答
  •  温柔的废话
    2020-12-29 09:04

    Generally, it will be difficult to avoid some kind of conditional statement at some point to create an instance of the appropriate class.

    The benefit of polymorphism comes when you have multiple if-else statements in multiple places. The polymorphism encapsulates the conditional logic for you. See this question for some other discussions on this topic.

    This sort of scattered logic:

    void initLayout() {
       if (user choose layoutA) { initialize layoutA }
       if (user choose layoutB) { initialize layoutB }
       if (user choose layoutC) {initialize layoutC }
    }
    
    void refreshLayout() {
       if (user choose layoutA) { refresh layoutA }
       if (user choose layoutB) { refresh layoutB }
       if (user choose layoutC) { refresh layoutC }
    }
    
    void cleanupLayout() {
       if (user choose layoutA) { cleanup layoutA }
       if (user choose layoutB) { cleanup layoutB }
       if (user choose layoutC) { cleanup layoutC }
    }
    

    Gets replaced with something simpler:

       layout = getLayout(user choice);
    
       layout.initLayout();
       layout.refreshLayout();
       layout.cleanupLayout();
    

提交回复
热议问题