简体   繁体   English

在服务层上使用接口

[英]Use of Interfaces on a service layer

In our project architecture we are using a classic MVC pattern including a classic service layer (opening the transaction and calling the DAO layer). 在我们的项目架构中,我们使用经典的MVC模式,包括经典服务层(打开事务并调用DAO层)。

For each service we have an implementation and his interface. 对于每个服务,我们都有一个实现和他的接口。 But to be honest, I'm pretty sure that for one service and his interface, we will never have more than one implementation. 但说实话,我很确定对于一个服务和他的界面,我们永远不会有多个实现。 So ok maybe it's more clear to have the public method declared in the interface helping to know what the service does, but an interface is used to have multiple implementation and if we know that we won't have more than one implementation, should we keep them? 好吧也许更清楚的是在界面中声明公共方法有助于知道服务的作用,但是接口用于多个实现,如果我们知道我们不会有多个实现,我们应该保持他们?

i think this is a good approach for keeping interfaces. 我认为这是保持接口的好方法。

reasons: 1. say you want to write junits for the same with a different implementations ex. 原因:1。说你想用不同的实现来编写相同的junits。 inspite of getting data from database you want to get data from a separate datasource then a different implementation will suffice. 尽管从数据库获取数据,您希望从单独的数据源获取数据,但是不同的实现就足够了。

From the documentation : 文档

Implementing an interface allows a class to become more formal about the behavior it promises to provide. 实现接口允许类对其承诺提供的行为变得更加正式。 Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. 接口在类和外部世界之间形成契约,并且该合同在构建时由编译器强制执行。

If you know that you will only have one implementation, the implementation itself will define the contract, so you can remove the interfaces. 如果您知道只有一个实现,那么实现本身将定义合同,因此您可以删除接口。

But writing an interface could help you to better define the contract and also, you could need at a given point to write a mock for the service, in such a case you would benefit from the use of interfaces. 但是编写接口可以帮助您更好地定义合同,并且您可能需要在给定点为服务编写模拟,在这种情况下,您将从接口的使用中受益。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM