閱讀259 返回首頁    go 阿裏雲 go 技術社區[雲棲]


依賴注入 概述

控製反轉: 一般分為兩種類型,依賴注入(Dependency Injection,簡稱DI)和依賴查找(Dependency Lookup)。

依賴注入:一種設計模式。一個類對另一個類有依賴時,由容器自動注入。


微笑以下內容來自百度知道

先看幾段代碼,都是Java
假設你編寫了兩個類,一個是人(Person),一個是手機(Mobile)。 
人有時候需要用手機打電話,需要用到手機的dialUp方法。 
傳統的寫法是這樣: 

public class Person{
    public boolean makeCall(long number){
        Mobile mobile=new Mobile();
        return mobile.dialUp(number);
    }
}

也就是說,類Person的makeCall方法對Mobile類具有依賴,必須手動生成一個新的實例new   Mobile()才可以進行之後的工作。 

依賴注入的思想是這樣,當一個類(Person)對另一個類(Mobile)有依賴時,不再該類(Person)內部對依賴的類(Moblile)進行實例化,而是之前配置一個beans.xml,告訴容器所依賴的類(Mobile),在實例化該類(Person)時,容器自動注入一個所依賴的類(Mobile)的實例。 

依賴注入寫法是這樣: 

接口: 
public Interface MobileInterface{
    public boolean dialUp(long number);
}

Person類: 
public class Person{
    private MobileInterface mobileInterface;
    public boolean makeCall(long number){
        return this.mobileInterface.dialUp(number);
    }
    public void setMobileInterface(MobileInterface mobileInterface){
        this.mobileInterface=mobileInterface;
    }

}


在xml文件中配置依賴關係 
<bean >
    <property name="mobileInterface">
        <ref local="mobileInterface"/>
    </property>    
</bean>

<bean />


這樣,Person類在實現撥打電話的時候,並不知道Mobile類的存在,它隻知道調用一個接口MobileInterface,而MobileInterface的具體實現是通過Mobile類完成,並在使用時由容器自動注入,這樣大大降低了不同類間相互依賴的關係。

最後更新:2017-04-03 05:40:19

  上一篇:go HTML 概述
  下一篇:go [麵試題]sizeof與strlen的區別