執行個體講解Java的Spring架構中的控制反轉和依賴注入_java

來源:互聯網
上載者:User

近來總是接觸到 IoC(Inversion of Control,控制反轉)、DI(Dependency Injection,依賴注入)等編程原則或者模式,而這些是著名 Java 架構 Spring、Struts 等的核心所在。針對此查了 Wikipedia 中各個條目,並從圖書館借來相關書籍,閱讀後有些理解,現結合書中的講解以及自己的加工整理如下:
 

eg1
問題描述:
開發一個能夠按照不同要求產生Excel或 PDF 格式的報表的系統,例如日報表、月報表等等。
 
解決方案:
根據“面向介面編程”的原則,應該分離介面與實現,即將產生報表的功能提取為一個通用介面ReportGenerator,並提供產生 Excel 和 PDF格式報表的兩個實作類別 ExcelGenerator 和 PDFGenerator,而客戶Client 再通過服務提供者 ReportService 擷取相應的報表列印功能。
 
實現方法:
根據上面所述,得到如下類圖:

代碼實現:
 

interface ReportGenerator {  public void generate(Table table); }  class ExcelGenerator implements ReportGenerator {  public void generate(Table table) {   System.out.println("generate an Excel report ...");  } }  class PDFGenerator implements ReportGenerator {  public void generate(Table table) {   System.out.println("generate an PDF report ...");  } }  class ReportService {  // 負責建立具體需要的報表產生器  private ReportGenerator generator = new PDFGenerator();  // private static ReportGenerator generator = new ExcelGenerator();    public void getDailyReport(Date date) {   table.setDate(date);   // ...   generator.generate(table);  }    public void getMonthlyReport(Month month) {   table.setMonth(month);   // ...   generator.generate(table);  } }   public class Client {  public static void main(String[] args) {   ReportService reportService = new ReportService();   reportService.getDailyReport(new Date());   //reportService.getMonthlyReport(new Date());  } } 

 
eg2 
問題描述:
如上面代碼中的注釋所示,具體的報表產生器由 ReportService 類內部寫入程式碼建立,由此 ReportService 已經直接依賴於 PDFGenerator 或 ExcelGenerator ,必須消除這一明顯的緊耦合關係。
 
解決方案:引入容器
引入一個中間管理者,也就是容器(Container),由其統一管理報表系統所涉及的對象(在這裡是組件,我們將其稱為 Bean),包括 ReportService 和各個 XXGenerator 。在這裡使用一個鍵-值對形式的 HashMap 執行個體來儲存這些 Bean。
 
實現方法:
得到類圖如下:

代碼實現:

class Container {  // 以鍵-值對形式儲存各種所需組件 Bean  private static Map<String, Object> beans;    public Container() {   beans = new HashMap<String, Object>();      // 建立、儲存具體的報表生起器   ReportGenerator reportGenerator = new PDFGenerator();   beans.put("reportGenerator", reportGenerator);      // 擷取、管理 ReportService 的引用   ReportService reportService = new ReportService();   beans.put("reportService", reportService);  }    public static Object getBean(String id) {   return beans.get(id);  } }  class ReportService {  // 消除緊耦合關係,由容器取而代之  // private static ReportGenerator generator = new PDFGenerator();  private ReportGenerator generator = (ReportGenerator) Container.getBean("reportGenerator");   public void getDailyReport(Date date) {   table.setDate(date);   generator.generate(table);  }    public void getMonthlyReport(Month month) {   table.setMonth(month);   generator.generate(table);  } }  public class Client {  public static void main(String[] args) {   Container container = new Container();   ReportService reportService = (ReportService)Container.getBean("reportService");   reportService.getDailyReport(new Date());   //reportService.getMonthlyReport(new Date());  } } 

 
時序圖大致如下:

效果:
如上面所示,ReportService 不再與具體的 ReportGenerator 直接關聯,已經用容器將介面和實現隔離開來了,提高了系統組件 Bean 的重用性,此時還可以使用設定檔在 Container 中即時擷取具體組件的定義。
 
eg3
問題描述:
然而,觀察上面的類圖,很容易發現 ReportService 與 Container 之間存在雙向關聯,彼此互相有依賴關係。並且,如果想要重用 ReportService,由於它也是直接依賴於單獨一個 Container 的具體尋找邏輯。若其他容器具體不同的組件尋找機制(如 JNDI),此時重用 ReportService 意味著需要修改 Container 的內部尋找邏輯。
 
解決方案:引入 Service Locator
再次引入一個間接層 Service Locator,用於提供組件尋找邏輯的介面,請看Wikipedia 中的描述 或者 Java EE 對其的描述1 、描述2 。這樣就能夠將可能變化的點隔離開來。
 
實現方法:
類圖如下:

代碼實現:
 

// 實際應用中可以是用 interface 來提供統一介面 class ServiceLocator {  private static Container container = new Container();    public static ReportGenerator getReportGenerator() {   return (ReportGenerator)container.getBean("reportGeneraator");  } }  class ReportService {  private ReportGenerator reportGenerator = ServiceLocator.getReportGenerator();    // ... } 


eg4

問題描述:
然而,不管是引入 Container 還是使用 Service Locator ,ReportService 對於具體組件的尋找、建立的方式都是‘主動'的,這意味著作為客戶的 ReportService 必須清楚自己需要的是什麼、到哪裡擷取、如何擷取。一下子就因為 What、Where、How 而不得不增加了具體邏輯細節。
 
例如,在前面‘引入Container '的實現方法中,有如下代碼: 

class ReportService { // 消除緊耦合關係,由容器取而代之 // private static ReportGenerator generator = new PDFGenerator(); // 通過 Container..getBean("reportGenerator") ‘主動'尋找 private ReportGenerator generator = (ReportGenerator) Container   .getBean("reportGenerator");

 
在‘引入 Service Locator '的實現方法中,有如下代碼: 

class ServiceLocator { privatestatic Container container = new Container();  publicstatic ReportGenerator getReportGenerator() {  // 還是container.getBean(), 用了委託而已  return (ReportGenerator) container.getBean("reportGeneraator"); }} class ReportService { // ReportService 最終還是‘主動'尋找,委託給ServiceLocator 而已 private ReportGenerator reportGenerator = ServiceLocator.getReportGenerator(); }

 
解決方案:
在這種情況下,變‘主動'為‘被動'無疑能夠減少 ReportService 的內部知識(即尋找組件的邏輯)。根據控制反轉(IoC)原則,可江此種拉(Pull,主動的)轉化成推(Push,被動的)的模式。
 
例如,平時使用的 RSS 訂閱就是Push的應用,省去了我們一天好幾次登入自己喜愛的網站主動擷取文章更新的麻煩。
 
而依賴注入(DI)則是實現這種被動接收、減少客戶(在這裡即ReportService)自身包含複雜邏輯、知曉過多的弊病。
 
實現方法:
因為我們希望是‘被動'的接收,故還是回到 Container 的例子,而不使用 Service Locator 模式。由此得到修改後的類圖如下:

而原來的類圖如下,可以對照著看一下,注意注釋的提示:

代碼實現:
為了使例子能夠編譯、運行,並且稍微利用跟蹤代碼的運行結果來顯式整個類圖執行個體化、互相協作的先後順序,在各個類的構造器中加入了不少已編號的列印語句,以及兩個無關緊要的類,有點囉唆,具體如下: 

import java.util.Date;import java.util.HashMap;import java.util.Map; // 為了能夠編譯運行,多了兩個無關緊要的類class Month { }class Table { publicvoid setDate(Date date) { } publicvoid setMonth(Month month) { }} // ------------ 以下均無甚重要改變 ----------------- //interface ReportGenerator { publicvoid generate(Table table);} class ExcelGenerator implements ReportGenerator {  public ExcelGenerator() {  System.out.println("2...開始初始化 ExcelGenerator ..."); }  publicvoid generate(Table table) {  System.out.println("generate an Excel report ..."); }} class PDFGenerator implements ReportGenerator {  public PDFGenerator() {  System.out.println("2...開始初始化 PDFGenerator ..."); }  publicvoid generate(Table table) {  System.out.println("generate an PDF report ..."); }}//------------ 以上均無甚重要改變 ----------------- // class Container { // 以鍵-值對形式儲存各種所需組件 Bean privatestatic Map<String, Object> beans;  public Container() {  System.out.println("1...開始初始化 Container ...");   beans = new HashMap<String, Object>();   // 建立、儲存具體的報表生起器  ReportGenerator reportGenerator = new PDFGenerator();  beans.put("reportGenerator", reportGenerator);   // 擷取、管理 ReportService 的引用  ReportService reportService = new ReportService();  // 注入上面已建立的具體 ReportGenerator 執行個體  reportService.setReportGenerator(reportGenerator);  beans.put("reportService", reportService);   System.out.println("5...結束初始化 Container ..."); }  publicstatic Object getBean(String id) {  System.out.println("最後擷取服務元件...getBean() --> " + id + " ...");  returnbeans.get(id); }} class ReportService {  // private static ReportGenerator generator = new PDFGenerator(); // 消除上面的緊耦合關係,由容器取而代之 // private ReportGenerator generator = (ReportGenerator) Container //   .getBean("reportGenerator");  // 去除上面的“主動”尋找,提供私人欄位來儲存外部注入的對象 private ReportGenerator generator;  // 以 setter 方式從外部注入 publicvoid setReportGenerator(ReportGenerator generator) {  System.out.println("4...開始注入 ReportGenerator ...");  this.generator = generator; }  private Table table = new Table();  public ReportService() {  System.out.println("3...開始初始化 ReportService ..."); }  publicvoid getDailyReport(Date date) {  table.setDate(date);  generator.generate(table); }  publicvoid getMonthlyReport(Month month) {  table.setMonth(month);  generator.generate(table); }} publicclass Client { publicstaticvoid main(String[] args) {  // 初始化容器  new Container();  ReportService reportService = (ReportService) Container    .getBean("reportService");  reportService.getDailyReport(new Date());  // reportService.getMonthlyReport(new Date()); }}

 
運行結果:

1...開始初始化 Container ...2...開始初始化 PDFGenerator ...3...開始初始化 ReportService ...4...開始注入 ReportGenerator ...5...結束初始化 Container ...最後擷取服務元件...getBean() --> reportService ...generate an PDF report ...

 
注意:
1、根據上面運行結果的列印順序,可見代碼中加入的具體編號是合理的,類比了程式執行的流程,於是也就不再畫順序圖表了。
2、注意該例子中對IoC、DI的使用,是以ReportService為用戶端(即組件需求者)為基點的,而代碼中的Client 類main()中的測試代碼才是服務元件的終端使用者,但它需要的不是組件,而是組件所具有的服務。
3、實際在Spring框剪中,初始化Container顯然不是終端使用者Client應該做的事情,它應該由服務提供者事先啟動就緒。
4、在終端使用者Client中,我們還是用到Container.getBean("reportService")來擷取事先已在Container的建構函式中執行個體化好的服務元件。而在具體應用中,通常是用XML等設定檔將可用的服務元件部署到伺服器中,再由Container讀取該設定檔結合反射技術得以建立、注入具體的服務元件。
 
分析:
之前是由ReportService主動從Container中請求擷取服務元件,而現在是被動地等待Container注入(Inject,也就是Push)服務元件。控制權明顯地由底層模組(ReportService 是組件需求者)轉移給高層模組(Container 是組件提供者),也就是控制反轉了。
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.