不安全如何重构重复的代码

时间:2013-12-09 12:38:12

标签: java swing refactoring

我正在尝试重构一个旧的遗留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中使用(超过20种形式)。每个Jdialog都有一个属性更改侦听器,它根据硬件设备的作用与gui交互。大多数时候这些改变听众都是平等的,但也有一些例外。

我的第一个目的是将所有这些代码(除了监听器)移动到超类,但我不安全,因为我不知道超级类是最好的Jdialog和Jpanel一次...

也许这是避免代码重复的更好方法。

如果这个问题有明显的答案,请原谅我的不好意思。对不起。

祝你好运

1 个答案:

答案 0 :(得分:1)

超类不起作用(通常情况下代码重用是一个坏主意)

创建一个包含重复方法的新类。新课程将依赖VerySpecialHardwareDevice

您的对话框和框架将取决于新课程,但不再取决于VerySpecialHardwareDevice

在新类中创建一个新的单个方法,该方法调用15个重复的方法。您的对话框和框架将调用该方法。

对于监听器,您可能希望创建可由框架和对话框使用的单独顶级类。您可能必须创建一个通过框架和对话框实现的公共接口,以及由侦听器调用的方法。

相关问题