欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Item 18: Prefer interfaces to abstract classes

程序员文章站 2022-04-16 20:23:04
...

1.  Existing classes can be easily retrofitted to implement a new interface.

 

2.  Interfaces are ideal for defining mixins.

 

3.  A mixin is a type that a class can implement in addition to its “primary type” to declare that it provides some optional behavior. For example, Comparable is a mixin interface that allows a class to declare that its instances are ordered with respect to other mutually comparable objects.

 

4.  Interfaces allow the construction of nonhierarchical type frameworks.

 

5.  Using interfaces to define types does not prevent you from providing implementation assistance to programmers. You can combine the virtues of interfaces and abstract classes by providing an abstract skeletal implementation class to go with each nontrivial interface that you export. (i.e. AbstractCollection, AbstractSet, AbastractMap, AbstractList, etc.)

 

6.  For most implementors of an interface, extending the skeletal implementation is the obvious choice. Furthermore, the skeletal implementation can still aid the implementor’s task if the class implementing the interface is implemented manually. It can forward invocations of interface methods to a contained instance of a private inner class that extends the skeletal implementation. This technique, known as simulated multiple inheritance, is closely related to the wrapper class idiom discussed in Item 16. It provides most of the benefits of multiple inheritance, while avoiding the pitfalls.

 

7.  Writing a skeletal implementation is relatively simple. First you must study the interface and decide which methods are the primitives in terms of which the others can be implemented. These primitives will be the abstract methods in your skeletal implementation. Then you must provide concrete implementations of all the other methods in the interface.

 

8.  A simple implementation is like a skeletal implementation in that it implements an interface and is designed for inheritance, but it differs in that it isn’t abstract: it is the simplest possible working implementation.(i.e. AbstractMap.SimpleEntry)

 

9.  It is far easier to evolve an abstract class than an interface. Once an interface is released and widely implemented, it is almost impossible to change.

 

10.  An interface is generally the best way to define a type that permits multiple implementations. An exception to this rule is the case where ease of evolution is deemed more important than flexibility and power. If you export a nontrivial interface, you should strongly consider providing a skeletal implementation to go with it. Finally, you should design all of your public interfaces with the utmost care and test them thoroughly by writing multiple implementations.