Why do most system architects insist on first programming to an interface?

后端 未结 16 2328
离开以前
离开以前 2020-12-05 00:32

Almost every Java book I read talks about using the interface as a way to share state and behaviour between objects that when first \"constructed\" did not seem to share a r

16条回答
  •  感情败类
    2020-12-05 01:08

    Programming to interfaces provides several benefits:

    1. Required for GoF type patterns, such as the visitor pattern

    2. Allows for alternate implementations. For example, multiple data access object implementations may exist for a single interface that abstracts the database engine in use (AccountDaoMySQL and AccountDaoOracle may both implement AccountDao)

    3. A Class may implement multiple interfaces. Java does not allow multiple inheritance of concrete classes.

    4. Abstracts implementation details. Interfaces may include only public API methods, hiding implementation details. Benefits include a cleanly documented public API and well documented contracts.

    5. Used heavily by modern dependency injection frameworks, such as http://www.springframework.org/.

    6. In Java, interfaces can be used to create dynamic proxies - http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/Proxy.html. This can be used very effectively with frameworks such as Spring to perform Aspect Oriented Programming. Aspects can add very useful functionality to Classes without directly adding java code to those classes. Examples of this functionality include logging, auditing, performance monitoring, transaction demarcation, etc. http://static.springframework.org/spring/docs/2.5.x/reference/aop.html.

    7. Mock implementations, unit testing - When dependent classes are implementations of interfaces, mock classes can be written that also implement those interfaces. The mock classes can be used to facilitate unit testing.

提交回复
热议问题