Re: [問題] mvc裡service的用途

看板java作者 (pcman)時間7年前 (2017/05/29 15:40), 7年前編輯推噓2(200)
留言2則, 2人參與, 最新討論串2/3 (看更多)
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://www.ptt.cc/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

05/30 05:25, , 1F
大概了解了 謝謝
05/30 05:25, 1F

11/13 19:38, , 2F
Autowired 少了 d
11/13 19:38, 2F
文章代碼(AID): #1PAz1pmC (java)
文章代碼(AID): #1PAz1pmC (java)