简体   繁体   English

单一方法类与接口实现

[英]Single method Class vs Interface implementation

Imagine the following Interface: 想象一下以下界面:

public interface ActivationFunction {
    double calculate(double value);
}

with two similar implementations: 有两个类似的实现:

Class based: 基于类:

public class SignFunction implements ActivationFunction {
    @Override
    public double calculate(double value) {
        return value >= 0.0 ? 1.0 : -1.0;
    }
}
...
final SignFunction signFunction = new SignFunction();

Interface based: 基于接口:

public interface SignFunction extends ActivationFunction {
    @Override
    default double calculate(double value) {
        return value >= 0.0 ? 1.0 : -1.0;
    }
}
...
final SignFunction signFunction = new SignFunction() {
};

Which of them is preferable and why? 其中哪一个更可取,为什么?

Appreciate for your opinion 感谢您的意见

Both work just fine so to some extent its just a matter of personal preference and how it will be used in your application. 两者都可以正常工作,因此在某种程度上仅是个人喜好以及如何在您的应用程序中使用它的问题。 In a similar situation I would pick one of the mechanisms and use it until it became clear that one method was more appropriate than the other. 在类似的情况下,我会选择一种机制并使用它,直到很明显一种方法比另一种方法更合适。

If you want to try and make the "correct" decision now then the main advantage (in my opinion anyway) of the interface mechanism is that it allows the behaviour of classes to be composed from multiple interfaces. 如果您现在想尝试做出“正确”的决定,那么接口机制的主要优点(无论如何,以我的观点)是它允许类的行为由多个接口组成。 You could have a class that gets implementation of functions from multiple interfaces which you can't do through plain old class inheritance. 您可能有一个从多个接口获取函数实现的类,而这些接口是无法通过普通的旧类继承来实现的。

The other advantage is that it forces the functions to be stateless which makes debugging them and understanding them easier. 另一个优点是,它强制功能为无状态,这使得调试和理解它们变得更加容易。 It's also less likely that someone will introduce state into your functions needlessly. 也不太可能有人将状态不必要地引入到您的函数中。

The downside, as illustrated by another answer to this post, is that not all developers realise that you can have implementation in an interface so you might get some push back from other developers. 不利的一面是,并非所有开发人员都意识到您可以在接口中实现,因此,可能并非所有开发人员都意识到可以从其他开发人员那里得到一些回击。

You will also need to instantiate an object somewhere to be able to call the method on the interface. 您还需要在某个地方实例化一个对象,以便能够在接口上调用该方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM