需要Dao和服务接口 [英] Need Of Dao And Service Interfaces

查看:242
本文介绍了需要Dao和服务接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是初学Mvc的新手,在很多教程中我发现有这样的Dao界面

I am new to spring Mvc and in a lot of tutorials i found there is a Dao interface like this

public interface StudentDAO {

public List<Student> getStudents();
public void addEntry(Student student);
public void updateEntry(Student student);
public void deleteEntry(Student student);
public Student getStudentById(int id);

}

以及此类服务

public interface StudentService {

public List<Student> getStudents();
public void addEntry(Student student);
public void updateEntry(Student student);
public void deleteEntry(Student student);
public Student getStudentById(int id);

}

并且有实现这些接口。我的问题是为什么我们需要接口而不是直接实现类?

and there are implementations for these interfaces. My Question is Why we need interfaces rather than direct implementation classes?.

推荐答案

也许最简单的具体例子就是测试。

Perhaps the simplest concrete illustration for the need is testing.

使用DAO接口,您可以测试应用程序的逻辑,而无需运行可从运行测试的计算机访问的数据库,只需在测试期间将DAO实现交换为虚拟实现。然后,该虚拟实现可以为测试运行之间不会改变的测试提供一致的数据,不能在DB中意外覆盖,在Git / SVN /等等中进行版本化。

With the DAO interface, you can test your application's logic without the need to have a DB running that's accessible from the machine running tests, simply by swapping your DAO implementation for a dummy one during tests. That dummy implementation can then provide consistent data for tests that doesn't change between test runs, cannot be overwritten in DB by accident, is versioned in you Git/SVN/whatever etc.

一般情况下,这是编程到界面,而不是实现设计原则。

In general, this is part of the Program to an interface, not an implementation design principle.

根据我的经验,即使你',这种界面与实现的分离也是一个好主意。永远不会有多个实现,因为它鼓励程序员更深入地思考类的契约

In my experience, this separation of interface vs. implementation is a good idea even if you're never going to have multiple implementations, because it encourages programmers to think more deeply about the contract of the class.

注意原则是不是普遍接受的,这里有一些反驳例如。

Note that the principle is not universally accepted, here are some counter-arguments for example.

这篇关于需要Dao和服务接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆