我们如何确定是否为接口方法提供默认的空实现(Defender方法)?

时间:2020-02-21 08:42:19

标签: java

当前,我有一个看起来像这样的界面

public interface SortInfoDialogListener {
    void onSortInfoSelected(SortInfo sortInfo);
    void onSortInfoDialogDismiss(DialogInterface dialog);
}

由于大多数实现者对onSortInfoDialogDismiss不感兴趣,我想知道,我是否应该将其作为一个空的防御者方法?

public interface SortInfoDialogListener {
    void onSortInfoSelected(SortInfo sortInfo);
    default void onSortInfoDialogDismiss(DialogInterface dialog) {
    }
}

我想知道,在使接口函数具有空的防御者方法之前,我还应该考虑哪些因素?

我尝试在有效Java 3项目20和项目21中找到答案。但是,仍然不能得出具体结论。

1 个答案:

答案 0 :(得分:5)

SOLID原则规定根据要求隔离接口。目前,我可以看到许多实现者不需要onSortInfoDialogDismiss方法。

尝试将onSortInfoDialogDismiss()提取到另一个接口,以便可以按需实现。

仅通过onSortInfoSelected()保留当前接口,如下所示。

public interface SortInfoDialogListener {
    void onSortInfoSelected(SortInfo sortInfo);
}

希望这会有所帮助。

相关问题