且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java:使用多态来避免if语句?

更新时间:2023-11-10 11:17:10

通常,在某些时候很难避免某种条件语句来创建适当类的实例。

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

当多个地方有多个if-else语句时,就会产生多态性的好处。多态性为您封装了条件逻辑。有关此主题的其他讨论,请参见此问题

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.

这种分散的逻辑:

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 }
}

替换为更简单的东西:

   layout = getLayout(user choice);

   layout.initLayout();
   layout.refreshLayout();
   layout.cleanupLayout();