完美的系统不是不需要再增加东西,而是不能再减少东西
在前面的例子中,我们说了学渣要完成作业必须要依赖学霸。那么学霸应该怎么把自己的作业交给学渣呢?(依赖注入)
进行依赖注入有三种方式:
1、构造方法依赖注入
public class StupidStudent { private SmartStudent smartStudent; public StupidStudent(SmartStudent smartStudent) { this.smartStudent = smartStudent; } public doHomewrok() { smartStudent.doHomework(); System.out.println(“学渣抄作业”); } }
public class StudentTest { public static void main(String[] args) { SmartStudent smartStudent = new SmartStudent(); StupidStudent stupidStudent = new StupidStudent(smartStudent); stupidStudent.doHomework(); } }
这种方式好比学渣从一开始就赖上了一个学霸,并且和这个学霸建立了长期合作关系。
2、setter方法注入
public class StupidStudent { private SmartStudent smartStudent; public void setSmartStudent(SmartStudent smartStudent) { this.smartStudent = smartStudent; } public doHomewrok() { smartStudent.doHomework(); System.out.println(“学渣抄作业”); } }
public class StudentTest { public static void main(String[] args) { SmartStudent smartStudent = new SmartStudent(); StupidStudent stupidStudent = new StupidStudent(); stupidStudent.setSmartStudent(smartStudent); stupidStudent.doHomework(); } }
这种方式学霸和学渣只是暂时的合作关系,如果学渣赖上了另一个学霸(调用set()方法传入了另一个对象),那么学渣和学霸的合作关系就结束了。
3、接口注入
public class StupidStudent { public void doHomewrok(SmartStudent smartStudent) { smartStudent.doHomework(); System.out.println(“学渣抄作业”); } }
public class StudentTest { public static void main(String[] args) { SmartStudent smartStudent = new SmartStudent(); StupidStudent stupidStudent = new StupidStudent(); stupidStudent.doHomework(smartStudent); } }
采用这种注入方式,学渣只是在做作业时,才临时抱佛脚地找一下学霸。
编辑于 08-10