我試圖重構一箇舊的遺留Java應用程序,並且我已經檢測到在項目中重複了很多次的代碼。我試圖把這個代碼放在一個地方,但我不知道最好的解決方案。不安全如何重構重複代碼
我的問題中的僞或多或少如下:
public class MYDialog extends JDialog{
private VerySpecialHardwareDevice my_device;
private int variable1;
private int variable3;
private int variableXX;
private PropertyChangeListener my_listener=new PropertyChangeListener(
{
//The code of the listener interacts with the swing elements of the dialog
//depending on the behaviour of the hardware device, and its
//different most of the Jdialogs/Jpanels, and its the same in a few of them.
};
public MyDialog(){
my_device=new VerySpecialHardwareDevice();
my_device.addPropertyChangeListener(my_listener);
}
/*Begin of the repeated method related with the special device*/
private void methodRelatedWithSpecialHardwareDevice1(){
//These methods and functions use some variables like variable 1, 2, etc
};
private void methodRelatedWithSpecialHardwareDevice2(){...};
private void methodRelatedWithSpecialHardwareDevice3(){...};
(...)
private void methodRelatedWithSpecialHardwareDevice15(){...};
/*************************************************************/
}
public class MYPanel extends JPanel{
private VerySpecialHardwareDevice my_device;
private int variable1;
private int variable3;
private int variableXX;
private PropertyChangeListener my_listener=new PropertyChangeListener(
{
//....
};
public MyPanel(){
my_device=new VerySpecialHardwareDevice();
my_device.addPropertyChangeListener(my_listener);
}
/*Begin of the repeated method related with the special device*/
private void methodRelatedWithSpecialHardwareDevice1(){
//These methods and functions use some variables like variable 1, 2, etc
};
private void methodRelatedWithSpecialHardwareDevice2(){...};
private void methodRelatedWithSpecialHardwareDevice3(){...};
(...)
private void methodRelatedWithSpecialHardwareDevice15(){...};
/*************************************************************/
}
正如你所看到的,這些方法都涉及到的硬件設備。從1到15的方法總是相同的,並且這個設備被用於許多不同的Jdialogs和Jpanels中,並且在應用程序中有超過二十種形式。每個Jdialog都有一個屬性更改監聽器,它會根據硬件設備的作用與gui進行交互。大多數時候這些變化的聽衆都是平等的,但有一些例外。我的第一個意圖是將所有這些代碼(除了監聽器)都移到一個超類中,但我不安全,因爲我不知道它的超類對於Jdialog和Jpanel是最好的......
也許這是一個更好的方法來避免這種代碼重複。
請原諒我的不好意思,如果這個問題有明顯的答案,請原諒我。
問候
可能,這應該去代碼審查 – secario
methodRelatedWithSpecialHardwareDevice *函數引用任何實例變量? – user987339
是的,函數引用與硬件設備相關的變量,但變量總是相同的(它們也是重複的),並且與對話框或面板無關。我認爲這些變量可以通過代碼移動到另一個地方。我將在我的示例中反映這一點。 –