Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

design patterns - what reasons are there to use interfaces (Java EE or Spring and JPA)

Most of the J2EE(Spring and JPA) classes are designed with interfaces. Except for inheritance, are there any technical reasons for this? Like dynamic proxy or AOP, I need more technical details about this

ex

public interface UserDAO {
   void delete();
   void update();
   void save();
   List<User> get();
}

public class UserDAOImpl implements UserDAO {
   public void delete(){}
   public void update(){}
   public void save(){}
   public List<User> get(){}
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are 3 main reasons, IMO:

First reason: proxies.

If you ask Spring for the bean of type UserDAO, it will in fact return a proxy encapsulating the actual UserDAOImpl instance. This allows it to demarcate transactions, verify security authorization, log accesses, compute statistics, etc. It's possible to do it without an interface, but then byte-code manipulation is needed.

Second reasons: testability.

When unit-testing a business service which uses a UserDAO, you typically inject a mock UserDAO implementation. Once again, this is easier to do when UserDAO is an interface. It's possible with a concrete class, but it has not always been, and it's still easier with an interface

Third reason: decoupling.

By using an interface, you have a place where you define the real contract of the DAO for its clients. Sure, it needs a setDataSource() method in the concrete implementation, but clients don't care about that. All they need is set of data-access methods offered by the DAO. By separating the interface and the concrete implementation, you make sure that the client doesn't rely on implementation details of the DAO.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...