如何更改java代码,以便它的子类定制,影响最小

0 java code-reuse refactoring design-patterns

我的代码有以下情况.

class A{

    public void putLogicHere(){

        //method is about 500 lines long.

        //Initial Few lines of code will be common 

        //middle part of code will be customized by its subclasses

        //Again here comes few lines of common code

    }
}

class B extends A{}
class C extends A{}
Run Code Online (Sandbox Code Playgroud)

在设计层面,我应该采取什么方法来进一步打破这个代码?考虑到方法的中间部分将由层次结构中的其他人自定义.

Chr*_*örz 5

我会让A abstract类成为一个类,并在其中创建一个抽象方法,如:

abstract void doAdditionalStuff(/*needed parameters from class A*/);
Run Code Online (Sandbox Code Playgroud)

并在A中使用它:

public void putLogicHere(){
    //Initial Few lines of code will be common 
    //Here use the abstract method implemented in subclasses
    doAdditionalStuff();

    //Again here comes few lines of common code

}
Run Code Online (Sandbox Code Playgroud)

然后,B类和C类可以实现该方法:

@Override
doAdditionalStuff() {
  //middle part of code will be customized by its subclasses
}
Run Code Online (Sandbox Code Playgroud)