课程名称:Java设计模式精讲 Debug方式+内存分析
课程章节:第3章 软件设计七大原则
主讲老师:Geely
课程内容:
问题1)依赖倒置原则定义
依赖倒置原则:高层模块不应该依赖底层模块,二者都应该依赖其抽象。
抽象不应该依赖细节,细节应该依赖抽象。
问题2)依赖倒置原则在实际中使用?
依赖倒置原则的实现:针对接口编程,不要针对实现编程。(尽量不要继承非抽象类,不要继承实现类)
在实际应用中的例子:
面向接口编程,可以让接口的实现类和接口的调用方法解耦。(例controller和service接口的具体实现解耦(controller中没有显现的调用service具体实现类,只是依赖service接口)。controller调用service接口,一个service接口对应一个业务,不需要业务逻辑写入到controller当中。如果不这样,所有的业务都写在controler当中,是很难维护的)
问题3)依赖倒置原则的目的是?
优点:可以减少类之间的耦合性(这是目的),提高扩展性(新的业务只需要实现接口),提高系统稳定性,提高代码可读性和维护性,可减低修改程序的风险。
问题4)理解了依赖倒置,就能明白aop,依赖注入。例子图片描述
面向接口编程目的:Controller和service接口实现解耦。图片描述
/**
* 版本1:
* 面向实现编程
* 这种方式就叫做面向实现编程:
* 实现类实现了什么,就直接调用什么。
* 缺点:每次更改业务,都得去该实现类。
*/
/* public static void main(String[] args) {
skController study = new skController();
study.studyJava();
study.studyUi();
study.studyPython();
}*/
/**
* 版本2:
* 面向接口编程:
* 注入方式:接口方法注入的方式。
*/
/* public static void main(String[] args) {
skController study = new skController();
study.studyCourse(new javaCourseService());
study.studyCourse(new uiCourseService());
}*/
/**
* 版本3:
* 面向接口编程。
* 注入方式:通过构造器注入。
* 缺点:通过构造器注入service,需要创建多个skController类才能注入多个service,因为在spring中默认是单例模式。
* 在service注入dao注入一次就可以。
* Controller注入service层注入一次也就可以。
* 所以显然通过构造器注入不合适,每次都要创建对象。
*
*/
/* public static void main(String[] args) {
skController study = new skController(new javaCourseService());
study.studyCourse();
skController studys = new skController(new uiCourseService());
study.studyCourse();
}*/
/**
* 版本4:
* 面向接口编程。
* 注入方式:通过setter注入。
*/
public static void main(String[] args) {
skController study = new skController();
study.setiCourseTest(new javaCourseService());
study.studyCourse();
study.iCourseTest(new uiCourseService());
study.studyCourse();
}
public class skController {
/**
* 这里只需要调用接口方法就可以。
*
* 接口作为参数,注入。
*/
public void studyCourse(ICourseTest iCourseTest){
iCourseTest.studyCourse();
}
/**
* 通过构造器注入。
* 构造器方法进行注入。studyCourse就不需要参数。
*/
ICourseTest iCourseTest;
public skController(ICourseTest iCourse){
iCourseTest = iCourse;
}
public void studyCourse(){
iCourseTest.studyCourse();
}
/**
* 通过setter注入方式。
*/
ICourseTest iCourseTest;
public void setiCourseTest(ICourseTest iCourseTest){
this.iCourseTest = iCourseTest;
}
public void studyCourse() {
iCourseTest.studyCourse();
}
}
