作者uopsdod (pcman)
看板java
标题Re: [问题] mvc里service的用途
时间Mon May 29 15:40:33 2017
MVC的目的概念上就是要将Controller与Model切开来
让所有与DB有关的Code变动都不需要调整到Controller的Code
而Service的功用,在你需要你的Model可以套上不同DB时特别有感觉。
假设你有MySql, Oracle, DB2三种DB, 你就能建一个Service像下面这样:
class PersonService{
@AutoWire
private PersonDaoInterface personDaoInterface;
public void insert(int name, int hobby){
Person personVO = new Person(name,hobby);
personDaoInterface.insert(personVO);
}
}
然後各自实作三个DB的class:
class PersonDao_Mysql implements PersonDaoInterface{...}
class PersonDao_Oracle implements PersonDaoInterface{...}
class PersonDao_DB2 implements PersonDaoInterface{...}
然後根据需求把这三个物件放给PersonService使用。
上面例子是使用Spring的@AutoWire方式注入,
也可以直接写死在PersonService里面,像是这样:
class PersonService{
// 挑一个来用
private PersonDaoInterface personDaoInterface = new PersonDao_MySql();
// private PersonDaoInterface personDaoInterface = new PersonDao_Oracle();
// private PersonDaoInterface personDaoInterface = new PersonDao_DB2();
// ...
}
如此一来
尽管变更DB,我们只要更换不同的Dao物件即可,也不会动到Controller的任何Code了。
这样就能达到更高一层的降低相依性。
※ 引述《yuxds (cody)》之铭言:
我看MVC架构里面
DAO的方法大多是丢入一个VO进去
而service的方法里面是new一个VO然後设定参数
最後再呼叫DAO的方法把VO丢进去
service的用途我记得好像是要降低相依性要好维护一点?
没有service的话那这部分就要搬到C里面
我上面讲的应该没错吧?
那我不太懂service带来的好处在哪边
可以说明一下或举个例子吗?
谢谢
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 180.217.143.71
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/java/M.1496043635.A.C0C.html
※ 编辑: uopsdod (180.217.143.71), 05/29/2017 15:41:50
※ 编辑: uopsdod (180.217.143.71), 05/29/2017 15:42:22
※ 编辑: uopsdod (180.217.143.71), 05/29/2017 15:43:53
※ 编辑: uopsdod (180.217.143.71), 05/29/2017 15:45:14
1F:推 yuxds: 大概了解了 谢谢 05/30 05:25
2F:推 wei810121: Autowired 少了 d 11/13 19:38