本文介绍了用 Java 重构代码,替代大型 if 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重构我正在处理的项目中的一些代码,我遇到了一个遵循以下格式的大型 if/else if 语句:

I'm refactoring some code in a project I'm working on and I ran into a large if/else if statement that follows the format:

if (changer instanceof AppleChanger)
{
   panel = new ApplePanel();
}
else if (changer instanceof OrangeChanger)
{
   panel = new OrangePanel();
}

现在我的第一个冲动是使用多态重构它,让它看起来像

Now my first impulse was to refactor it using polymorphism to have it appear like

panel = changer.getChangerPanel();

然而不幸的是,类包没有访问面板包的权限.

However unfortunately the class package doesn't have access to the panel package.

我的下一个冲动是创建一个带有重载方法的 PanelChooser 类:

My next impulse was to create a PanelChooser class with an overloaded method:

PanelChooser.getPanel(changer);

//Overloaded Method
public Panel getPanel(OrangeChanger changer)
{
   Panel orangePanel = new OrangePanel();
   return orangePanel;
}
public Panel getPanel(AppleChanger changer)
{
   Panel applePanel = new ApplePanel();
   return applePanel;
}

这是一个好的解决方案还是有更好的方法来解决这个问题?

Is this a good solution or is there a better way to solve this?

推荐答案

这里的基本问题"是您有并行的类层次结构.如果没有一些相当繁重的重构,您将无法替换该 if 语句.一些建议是 关于 c2 wiki.

The fundamental 'problem' here is that you have parallel class hierarchies. You're not going to be able to replace that if statement without some fairly heavy refactoring. Some suggestions are on c2 wiki.

您能做的最好的事情,也可能是一个完美的解决方案,就是将 if 语句移到工厂"类中,并确保它不会在其他任何地方重复.

The best you can do, and possibly a perfectly fine solution, is to move the if statement into a 'factory' class and make sure it's not duplicated anywhere else.

这篇关于用 Java 重构代码,替代大型 if 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 02:57