我曾多次看到有人提到这一点,但我不清楚这是什么意思。你什么时候,为什么要这么做?
我知道接口是做什么的,但我不清楚这一点的事实使我认为我错过了正确使用它们。
如果你要这样做
IInterface classRef = new ObjectWhatever()
你可以使用任何实现IInterface的类吗?你什么时候需要这样做?我能想到的唯一一件事是,如果你有一个方法,你不确定什么对象将被传递,除了它实现IInterface。我不知道你需要多久做一次。
另外,如何编写一个方法来接受实现接口的对象呢?这可能吗?
面向接口而不是实现的代码与Java无关,也与它的接口构造无关。
这个概念是在模式/四人帮的书中突出的,但很可能在那之前就已经存在了。这个概念在Java出现之前就已经存在了。
Java Interface构造的创建就是为了帮助实现这一想法(以及其他一些事情),人们过于关注作为意义中心的构造,而不是最初的意图。然而,这也是为什么我们在Java、c++、c#等语言中有公共和私有方法和属性的原因。
It means just interact with an object or system's public interface. Don't worry or even anticipate how it does what it does internally. Don't worry about how it is implemented. In object-oriented code, it is why we have public vs. private methods/attributes. We are intended to use the public methods because the private methods are there only for use internally, within the class. They make up the implementation of the class and can be changed as required without changing the public interface. Assume that regarding functionality, a method on a class will perform the same operation with the same expected result every time you call it with the same parameters. It allows the author to change how the class works, its implementation, without breaking how people interact with it.
And you can program to the interface, not the implementation without ever using an Interface construct. You can program to the interface not the implementation in C++, which does not have an Interface construct. You can integrate two massive enterprise systems much more robustly as long as they interact through public interfaces (contracts) rather than calling methods on objects internal to the systems. The interfaces are expected to always react the same expected way given the same input parameters; if implemented to the interface and not the implementation. The concept works in many places.
不要认为Java接口与“面向接口编程,而不是面向实现”的概念有什么关系。它们可以帮助应用概念,但它们不是概念。
当您拥有一组类似的类时,它使您的代码更具可扩展性,更容易维护。我是一个初级程序员,所以我不是专家,但我刚刚完成了一个需要类似东西的项目。
我从事与运行医疗设备的服务器对话的客户端软件工作。我们正在开发这种设备的新版本,其中有一些新组件,客户必须不时进行配置。有两种类型的新组件,它们是不同的,但也非常相似。基本上,我必须创建两个配置表单,两个列表类,所有东西都要创建两个。
我决定最好是为每个控件类型创建一个抽象基类,它可以容纳几乎所有的实际逻辑,然后是派生类型,以处理两个组件之间的差异。然而,如果我不得不一直担心类型,基类就不能在这些组件上执行操作(好吧,它们可以,但每个方法中都有一个“if”语句或开关)。
我为这些组件定义了一个简单的接口,所有基类都与该接口对话。现在当我改变一些东西,它几乎“只是工作”在任何地方,我没有代码复制。
让我们先从一些定义开始:
一个对象的操作所定义的所有签名的集合称为该对象的接口
输入n.指定接口
上面定义的接口的一个简单例子是所有PDO对象方法,如query()、commit()、close()等,作为一个整体,而不是分开。这些方法,即它的接口定义了可以发送到对象的完整消息和请求集。
上面定义的类型是一个特定的接口。我将使用创建的形状界面来演示:draw(), getArea(), getPerimeter()等。
如果一个对象是Database类型的,我们的意思是它接受数据库接口、query()、commit()等的消息/请求。对象可以有多种类型。只要实现了接口,就可以让数据库对象具有形状类型,在这种情况下,这将是子类型。
许多对象可以是许多不同的接口/类型,并以不同的方式实现该接口。这允许我们替换对象,让我们选择使用哪个对象。也称为多态性。
客户机将只知道接口,而不知道实现。
因此,从本质上讲,编程到一个接口将涉及到一些类型的抽象类,如只指定接口的Shape,即draw(), getCoordinates(), getArea()等。然后让不同的具体类实现这些接口,比如圆形类,方形类,三角形类。因此,针对接口而不是实现编程。