【问题标题】:how to change a java code so that it will be customized by its subclasses with minimal impact如何更改 Java 代码,以便它可以由其子类自定义而影响最小
【发布时间】:2018-07-27 05:05:30
【问题描述】:

我的代码有以下情况。

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{}

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

【问题讨论】:

    标签: java design-patterns refactoring code-reuse


    【解决方案1】:

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

    abstract void doAdditionalStuff(/*needed parameters from class A*/);
    

    并在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
    
    }
    

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

    @Override
    doAdditionalStuff() {
      //middle part of code will be customized by its subclasses
    }
    

    【讨论】:

    • 感谢您的回答。我在这里有一个问题-在您提到的设计中,我们如何将junit编写为抽象的超类?
    • @VRK 只需在您的测试源中创建一个子类或使用一个模拟框架。例如。使用 mockito,您可以创建抽象类的 mock,并告诉 mockito 调用真实方法。但我认为这是你应该问的另一个问题。
    • 感谢@RenéLink!
    【解决方案2】:

    对业务逻辑有一个概念

    • 提供服务
    • 要求(生产某些东西)resp。 回调(作出反应)提供(实施)

    所以:

    (abstract) class Base {
        public final void oneService() {
            ...
            U u = requirementX(X x);
            ...
            V v = requirementY(Y y);
            ...
        }
        protected U requirementX(X x) {
        }
        abstract protected V requirementY(Y y);
    }
    
    class Aaa extends Base { ... }
    class Bbb extends Base { ... }
    

    注意:

    • 服务可能是最终的
    • 需求可以受到保护,应该被覆盖,并且可以具有由基类准备的额外上下文参数。

    使用 Java 8 代替受保护方法的继承,设置一些函数指针/lambda 参数有时可能会更好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-02
      • 2020-12-19
      • 1970-01-01
      • 2011-11-03
      • 2023-04-08
      • 2021-10-08
      相关资源
      最近更新 更多