2013-12-09 59 views
0

我試圖重構一箇舊的遺留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是最好的......

也許這是一個更好的方法來避免這種代碼重複。

請原諒我的不好意思,如果這個問題有明顯的答案,請原諒我。

問候

+2

可能,這應該去代碼審查 – secario

+0

methodRelatedWithSpecialHardwareDevice *函數引用任何實例變量? – user987339

+0

是的,函數引用與硬件設備相關的變量,但變量總是相同的(它們也是重複的),並且與對話框或面板無關。我認爲這些變量可以通過代碼移動到另一個地方。我將在我的示例中反映這一點。 –

回答

1

使用超是不行的(並且是在一般情況下,代碼重用一個壞主意)

創建一個新類牽着你重複的方法。新課改將有VerySpecialHardwareDevice

你對話和框架的依賴將取決於新的類,但在VerySpecialHardwareDevice

在新的類不再創造它調用15層複製的方法一個新的單一方法。你的對話框和框架將調用該方法。

對於Listeners,您可能希望創建可通過框架和對話框使用的獨立頂級類。您可能必須創建一個通過框架和對話框實現的通用接口,以及偵聽器調用的方法。