[英]How do I Design and Interface (OOP kind) in Java so that I can either use direct database access or use web services?
At the moment I have to query database that I do not own which has a web service, so what they provide is what I get. 目前我必须查询我不拥有的具有Web服务的数据库,因此他们提供的是我得到的。 Since this is in house (sort of), I might be able to get direct access in the future so that I can get better data in my query. 由于这是内部的(有点),我可能会在将来获得直接访问权限,以便我可以在查询中获得更好的数据。
I don't want to have to write everything again and again. 我不想一次又一次地写一切。 If I did this in Java would I write an Interface (programming kind, think Implements Interface, OOP)? 如果我在Java中这样做,我会编写一个接口(编程类型,想想Implements Interface,OOP)? How would I do this? 我该怎么做? Or do I just write a whole new class and "plug it in." 或者我只是写一个全新的类并“插入它”。
This is just a regular client/server architecture. 这只是一个常规的客户端/服务器架构。 Http request, server calls the servlet or jsp, returns data. Http请求,服务器调用servlet或jsp,返回数据。
I'm not sure if my idea is correct design or not. 我不确定我的想法是否是正确的设计。
Definitely sounds like you should use an interface with different implementations here. 绝对听起来你应该在这里使用具有不同实现的接口。 Something like: 就像是:
public interface DataAccess {
Data getData();
}
Then you can code against this API and just plugin/inject a different implementation as needed. 然后,您可以针对此API进行编码,并根据需要插入/注入不同的实现。 So you could have this: 所以你可以这样:
public class DirectDataAccess implements DataAccess {
public Data getData() {
//use JDBC, ORM, or similar
}
}
Or this: 或这个:
public class WebServiceDataAccess implements DataAccess {
public Data getData() {
//call web service
}
}
But as long as your client code only references the DataAccess
interface, then you have successfully decoupled your client from your service. 但只要您的客户端代码仅引用DataAccess
接口,您就已成功将客户端与服务分离。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.