目的
使得一个类的行为由设置的属性类的行为不同而不同。
例子代码
从小到大,妈妈总是那个对家里东西最熟悉的人。
记得自己小时候是个小迷糊,经常找不到东西,总是问老妈,“妈,家里的剪刀在哪啊”,“妈,我那件卡通T恤呢”......妈妈就像个魔法师,总是能变出自己要找的东西。
后来长大了才明白,哪有什么魔法师,都是因为妈妈默默承包了所有家务,都是她帮我们这样的小迷糊整理收纳。
我们定义一个我们人这个类:People
(一)People 里面我们可以 new 一个 Mother,然后调用 mother 类的方法
(二)或者我们可以定义一个方法叫做 callMother(Mother mother) ,其中 Mather 类如下:
public interface Mother { String findThing();}
在里面调用 Mother 类的方法来输出 callMother 的效果问题分析。
问题分析
上面的代码一不够灵活, 而且 mother 是调用方法的时候创建,方法完成后需要垃圾回收,造成问题,而且改“妈妈”还得修改代码。
代码二提供了很好的灵活性,可是也提供了不必要的灵活性, 同一个孩子需要 call 方法可能会传入好几个妈的情况太少了,不需要提供这么大的灵活性, 而且妈妈基本上是孩子创建的时候就指定的了,这就是依赖注入的用处了。
依赖注入模式
@Datapublic class People { private String name; private Mother mother; public void callMother() { System.out.println(this.name + "的妈妈能" + mother.findThing()); }}
Mother 的二个子类:
public class BagMother implements Mother { @Override public String findThing() { return "找到书包"; }}
和
public class SockMother implements Mother { @Override public String findThing() { return "找到袜子"; }}
我们的使用:
public class App { public static void main(String[] args) { People lanlan = new People(); lanlan.setName("兰兰"); lanlan.setMother(new BagMother()); lanlan.callMother(); }}