gpt4 book ai didi

Java:具体空实例方法的继承

转载 作者:行者123 更新时间:2023-12-02 11:30:55 26 4
gpt4 key购买 nike

该问题被视为一般的面向对象设计问题,目前与任何具体案例无关。

假设我有一个具有抽象类的测试库:

public abstract class AbstractTest<E extends Event> {

private ProcessingService service = new ProcessingService();

protected static abstract void buildTestData();

public void testSomething(Event event) {
beforeScenario(event);

service.process(event);

// ... asserts and other actions

afterScenario(event);
}

protected void beforeScenario(E event) {
// override if needed
}

protected void afterScenario(E event) {
// override if needed
}
}

AbstractTest 派生的每个类都被迫提供 buildTestData() 实现,并且可以选择提供自己的 beforeScenarioafterScenario

从我的角度来看,拥有这样的空方法有它自己的优点和缺点。您不会将派生类创建为 @Override 可选方法,而不是抽象方法。此外,您还要确保调用场景的正确顺序,以防派生类覆盖它们并使用抽象类中的 testSomething :

public class SpecificTest extends AbstractTest<SomeEvent> {

protected static void buildTestData() {
// build test data
}

// override only scenarious and do not touch testSomething()
protected void beforeScenario(E event) {
// construct
}

protected void afterScenario(E event) {
// destroy
}
}

另一方面,这些空的具体方法在父类中看起来很奇怪。派生类可以@Override testSomething,例如:

public class SpecificTest extends AbstractTest<SomeEvent> {

protected static void buildTestData() {
// build test data
}

// assuming that you don't have these methods in parent classes
public void testSomething(Event event) {
beforeScenario(event);

super.testSomething(event);

afterScenario(event);
}


private void beforeScenario(E event) {
// construct
}

private void afterScenario(E event) {
// destroy
}
}

从 OOD 的角度来看,哪种方法更合适?

在父类中保留这样的空方法是否有意义?

最佳答案

你的做法没有任何问题。您的代码结构类似于 Template Pattern .

模板模式实现看起来像(取自 Head First Design Patterns)

abstract class AbstractClass {
final void templateMethod() {
primitiveOperation1();
primitiveOperation2();
concreteOperation();
hook();
}
abstract void primitiveOperation1();
abstract void primitiveOperation2();

final void concreteOperation() {
//implementation
}
void hook() { }
}

primitiveOperations 是抽象的,必须由子类重写,而concreteOperation 被标记为最终的并且不能被重写。我们还有一个名为 hook 的具体方法,它默认不执行任何操作。子类可以选择覆盖它或决定不覆盖它。这些方法称为钩子(Hook)。

因此,当将您的代码与此进行比较时

  • buildTestData 是一个primitiveOperation
  • testSomethingconcreteOperation
  • beforeScenarioafterScenariohook

关于Java:具体空实例方法的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49305146/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com