Java:具体空实例方法的继承
该问题被认为是一个一般的面向对象设计问题,目前与任何具体案例都不相关 假设我有一个测试库,它有一个抽象类:Java:具体空实例方法的继承,java,oop,Java,Oop,该问题被认为是一个一般的面向对象设计问题,目前与任何具体案例都不相关 假设我有一个测试库,它有一个抽象类: public abstract class AbstractTest<E extends Event> { private ProcessingService service = new ProcessingService(); protected static abstract void buildTestData(); public void
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
}
}
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
}
}
另一方面,这些空的具体方法在父类中看起来很奇怪。派生类可以覆盖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
}
}
公共类SpecificTest扩展了AbstractTest{
受保护的静态void buildTestData(){
//构建测试数据
}
//假设父类中没有这些方法
公共void testSomething(事件){
情景(事件)发生前;
super.testSomething(事件);
赛后(事件);
}
场景(E事件)之前的私有无效{
//构造
}
赛后私人空间(E事件){
//毁灭
}
}
从OOD的角度来看,哪种方法更合适?
在父类中保留这样的空方法有意义吗?您的方法没有错。您的代码结构类似于 模板模式实现看起来像(摘自Head-First设计模式)
primitiveOperations
是抽象的,必须由子类重写,concreteOperations
标记为final,不能重写。
我们还有一个名为hook的具体方法,默认情况下它什么都不做。子类可以选择覆盖它或决定不覆盖它。这些方法称为钩子
因此,当您将代码与此进行比较时
是一个buildTestData
基本操作
是testSomething
concreteOperation
和场景后是场景前
挂钩
testSomething(Event-Event)
标记为final
。
abstract class AbstractClass {
final void templateMethod() {
primitiveOperation1();
primitiveOperation2();
concreteOperation();
hook();
}
abstract void primitiveOperation1();
abstract void primitiveOperation2();
final void concreteOperation() {
//implementation
}
void hook() { }
}