这个UML图是否违反了接口隔离原则?

问题描述 投票:0回答:1

我创建了这个应用模板方法设计模式的 UML 图:

这两个具体类共享模板方法 createTask 和completeTask 中的许多逻辑,每个具体实现都有很小的变化,所以我选择了模板方法设计模式。然而,其中一个具体类不需要验证,因此它将抽象方法performValidations 实现为空的void 方法。

这是否违反了接口隔离原则?或者在这种情况下将具体类中这个抽象方法的实现留空可以吗?

java design-patterns solid-principles interface-segregation-principle
1个回答
0
投票

接口隔离原则的基本思想是子类不得实现与其无关的方法。在您的情况下,

performValidations
并不与所有子类完全相关,但他们需要为其提供实现;所以它确实违反了这个原则。

如果对您的域的用例没有太多背景,这将是我的建议。

您可以促进

performValidations
在抽象类本身中使用空实现主体来实现。需要进行一些验证的人只需重写该方法
performValidations
并提供自己的实现。通过这样做,
Open/Closed Principle
正在被应用。

也许一个更简洁的解决方案是拥有一个接口

Task
这样定义了
Task
的基本思想。

public interface Task {
    /**
     * Perform steps required to create a task
     * @return true if all the steps have executed successfully.
     */
    boolean createTask();

    /**
     * Perform validations required for a task.
     * @return true if validations are successful.
     */
    default boolean validateTask(){
      return true;   
    }

    /**
     * Perform steps required to complete a task
     * @return true if all the steps have executed successfully.
     */
    boolean completeTask();
}

引入一个方法

executeTask
也是有意义的。

© www.soinside.com 2019 - 2024. All rights reserved.