依赖注入 概述

控制反转: 一般分为两种类型,依赖注入(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 id="person" class="Person">
<property name="mobileInterface">
<ref local="mobileInterface"/>
</property>
</bean>

<bean id="mobileInterface" class="Mobile"/>

这样,Person类在实现拨打电话的时候,并不知道Mobile类的存在,它只知道调用一个接口MobileInterface,而MobileInterface的具体实现是通过Mobile类完成,并在使用时由容器自动注入,这样大大降低了不同类间相互依赖的关系。

相关文章

迭代器模式(Iterator)迭代器模式(Iterator)[Cursor]意图...
高性能IO模型浅析服务器端编程经常需要构造高性能的IO模型,...
策略模式(Strategy)策略模式(Strategy)[Policy]意图:定...
访问者模式(Visitor)访问者模式(Visitor)意图:表示一个...
命令模式(Command)命令模式(Command)[Action/Transactio...
生成器模式(Builder)生成器模式(Builder)意图:将一个对...