What does “program to interfaces, not implementations” mean?

前端 未结 7 2028
情深已故
情深已故 2020-11-22 07:41

One stumbles upon this phrase when reading about design patterns.

But I don\'t understand it, could someone explain this for me?

7条回答
  •  旧巷少年郎
    2020-11-22 08:09

    Think of an interface as a contract between an object and its clients. That is the interface specifies the things that an object can do, and the signatures for accessing those things.

    Implementations are the actual behaviours. Say for example you have a method sort(). You can implement QuickSort or MergeSort. That should not matter to the client code calling sort as long as the interface does not change.

    Libraries like the Java API and the .NET Framework make heavy use of interfaces because millions of programmers use the objects provided. The creators of these libraries have to be very careful that they do not change the interface to the classes in these libraries because it will affect all programmers using the library. On the other hand they can change the implementation as much as they like.

    If, as a programmer, you code against the implementation then as soon as it changes your code stops working. So think of the benefits of the interface this way:

    1. it hides the things you do not need to know making the object simpler to use.
    2. it provides the contract of how the object will behave so you can depend on that

提交回复
热议问题