当只有一个实现类时,为什么要使用接口?

Qai*_*hel 14 java implementation interface

我是编程新手,我正在学习Java.我只是想知道为什么我应该在只有一个实现类时使用接口?

das*_*ght 7

这样做是为了防止其他人访问您的实现类型.例如,您可以在库中隐藏实现类型,提供类型包访问,并将接口实例返回给库的用户:

// This is what the users of your library know about the class
// that does the work:
public interface SomeInterface {
    void doSomethingUseful();
    void doSomethingElse();
}

// This is the class itself, which is hidden from your clients
class MyImplementation implements SomeInterface {
    private SomeDependency dependency = new SomeDependency();
    public void doSomethingUseful() {
        ...
    }
    public void doSomethingElse() {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

您的客户获得如下对象:

public class MyFactory {
    static SomeInterface make() {
        // MyFactory can see MyImplementation
        return new MyImplementation();
    }
}
Run Code Online (Sandbox Code Playgroud)

当实现使用大量库时,这个技巧变得有用.您可以有效地将库的接口与其实现分离,以便用户不必了解库内部的依赖项.

  • 我没有看到将用户交给接口与将用户交给实现类之间的区别."外观和感觉"是一样的...... (3认同)

Raf*_*ael 6

你不应该在没有思考和推理的情况下做任何事情。

在某些情况下,您可能甚至想为单个实现添加一个接口……但在我看来,这是来自旧 EJB 时代的过时做法,人们在没有正确推理和反思的情况下使用和强制执行。

……马丁·福勒 (Martin Fowler)、阿丹·比恩 (Adan Bien) 和其他人多年来一直这么说。

https://martinfowler.com/bliki/InterfaceImplementationPair.html

https://www.adam-bien.com/roller/abien/entry/service_s_new_serviceimpl_why