编程到接口是什么意思? [英] What does it mean to program to a interface?

查看:95
本文介绍了编程到接口是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直听到大多数与节目相关的网站上的声明:

I keep hearing the statement on most programming related sites:


编程到接口而不是
实现

Program to an interface and not to an Implementation

但是我不明白其含义?

例子会有所帮助。

However I don't understand the implications?
Examples would help.

编辑:我收到了很多好的答案,所以你可以用一些代码片段来补充它,以便更好地理解这个主题。谢谢!

I have received a lot of good answers even so could you'll supplement it with some snippets of code for a better understanding of the subject. Thanks!

推荐答案

你可能正在寻找这样的东西:

You are probably looking for something like this:

public static void main(String... args) {
  // do this - declare the variable to be of type Set, which is an interface
  Set buddies = new HashSet();

  // don't do this - you declare the variable to have a fixed type
  HashSet buddies2 = new HashSet();
}

为什么第一种方式做得好?稍后我们说你决定需要使用不同的数据结构,比如LinkedHashSet,以便利用LinkedHashSet的功能。代码必须像这样更改:

Why is it considered good to do it the first way? Let's say later on you decide you need to use a different data structure, say a LinkedHashSet, in order to take advantage of the LinkedHashSet's functionality. The code has to be changed like so:

public static void main(String... args) {
  // do this - declare the variable to be of type Set, which is an interface
  Set buddies = new LinkedHashSet();  // <- change the constructor call

  // don't do this - you declare the variable to have a fixed type
  // this you have to change both the variable type and the constructor call
  // HashSet buddies2 = new HashSet();  // old version
  LinkedHashSet buddies2 = new LinkedHashSet();
 }

这看起来不是很糟糕,对吧?但是如果你以同样的方式写getter怎么办?

This doesn't seem so bad, right? But what if you wrote getters the same way?

public HashSet getBuddies() {
  return buddies;
}

这也必须改变!

public LinkedHashSet getBuddies() {
  return buddies;
}

希望您看到,即使是这样的小程序,您也有深远的影响对你声明变量类型的含义。如果你只是依赖于一个被声明为接口的变量,而不是作为该接口的特定实现(在这种情况下,声明它是一个接口),那么对象来回如此之多,肯定有助于使程序更容易编码和维护设置,而不是LinkedHashSet或其他)。可能就是这样:

Hopefully you see, even with a small program like this you have far-reaching implications on what you declare the type of the variable to be. With objects going back and forth so much it definitely helps make the program easier to code and maintain if you just rely on a variable being declared as an interface, not as a specific implementation of that interface (in this case, declare it to be a Set, not a LinkedHashSet or whatever). It can be just this:

public Set getBuddies() {
  return buddies;
}

还有另外一个好处,那个(至少对我而言)差异帮助我更好地设计程序。但希望我的例子给你一些想法......希望它有所帮助。

There's another benefit too, in that (well at least for me) the difference helps me design a program better. But hopefully my examples give you some idea... hope it helps.

这篇关于编程到接口是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆