Why do some APIs provide mostly interfaces, not classes?
Some Java APIs provide a large number of interfaces and few classes. For example开发者_如何学运维, the Stellent/Oracle UCM API is composed of roughly 80% interfaces/20% classes, and many of the classes are just exceptions.
What is the technical reason for preferring interfaces to classes? Is it just an effort to minimize coupling? To improve encapsulation/information hiding? Something else?
It would be to maximize their flexibility in changing the underlying classes behind the scenes.
As long as the interfaces/contracts remain the same, they can change the implementation classes all they want without worrying about affecting people who are using their library.
They are designed for 3rd parties to provide the implementation.
A classic and successful example is JDBC ( 22 interfaces 7 concrete classes )
The idea is to provide a .. well.. programmer interface ( API ) so the clients ( the ones that use the code ) may freely relay on the features these API provides without worrying about the underlying implementation.
Other reason is, there might be an existing provider ( ie. FutureSQL ) which still doesn't exist, but it may implement this interfaces and you'll be able to use it.
Its likely, the framework/API was developed with Dependency Injection, extensibility, low coupling and high cohesion in mind
The number of interfaces relative to the number of classes isn't really that important if each class implements a large number of the interfaces.
One of the best example is java.sql package.
The reason is: when the designer has a clear idea in mind as to what needs to be done and how the entire application [yet to be designed] structured they provide this idea through an API as a bunch of interfaces.
For example: when SUN (now oracle :-( ) publishes the API for JDBC, the entire SQL package (well most of it) is just interfaces with interoperability very well defined; but the actual vendor of the DB/RDBMS knows what to do so that they achieve the results as expected in the API.
Hence you can write ur java and DB interaction separately while the Database vendor writes the database separately. The vendor just has to write a driver that meets the API (interfaces) standard with out telling you how he did it.
Yet ur application and the DB interoperate with out any problem [well most of the time ;-)]
it's a long answer but hope this helps. Thanks,
Ayusman
精彩评论