依赖倒转原则
1)高层模块不应该依赖低层模块,而这应该依赖其抽象(接口,抽象类)
2)抽象不应该依赖细节,细节应该依赖抽象
3)依赖倒转(倒置)的中心思想面向接口编程
4)设计理念:相对于细节的多变性,抽象的东西要稳定得多,以抽象为基础搭建的架构比以细节搭建的架构要稳定的多.在Java中,抽象指的是接口或抽象类,细节就是具体的实现类.
5)使用接口和抽象类的目的是制定好规范,而不涉及任何具体的操作,把展现细节的任务教给他们的实现类去完成
依赖关系传递的三种方式
接口传递
public class DependecyInversion3 {
public static void main ( String[ ] args) {
OpenAndClose openAndClose = new OpenAndClose ( ) ;
openAndClose. open ( new TV ( ) ) ;
}
}
class TV implements ITV {
@Override
public void play ( ) {
System. out. println ( "打开电视机" ) ;
}
}
interface IOpenAndClose {
void open ( ITV itv) ;
}
interface ITV {
void play ( ) ;
}
class OpenAndClose implements IOpenAndClose {
@Override
public void open ( ITV itv) {
itv. play ( ) ;
}
}
构造方法传递
public class DependecyInversion4 {
public static void main ( String[ ] args) {
OpenAndClose openAndClose = new OpenAndClose ( new TV ( ) ) ;
openAndClose. open ( ) ;
}
}
class TV implements ITV {
@Override
public void play ( ) {
System. out. println ( "打开电视机" ) ;
}
}
interface IOpenAndClose {
void open ( ) ;
}
interface ITV {
void play ( ) ;
}
class OpenAndClose implements IOpenAndClose {
public ITV itv;
public OpenAndClose ( ITV itv) {
this . itv = itv;
}
@Override
public void open ( ) {
this . itv. play ( ) ;
}
}
setter方式传递
public class DependecyInversion5 {
public static void main ( String[ ] args) {
OpenAndClose openAndClose = new OpenAndClose ( ) ;
openAndClose. setItv ( new TV ( ) ) ;
openAndClose. open ( ) ;
}
}
class TV implements ITV {
@Override
public void play ( ) {
System. out. println ( "打开电视机" ) ;
}
}
interface IOpenAndClose {
void open ( ) ;
}
interface ITV {
void play ( ) ;
}
class OpenAndClose implements IOpenAndClose {
public ITV itv;
public void setItv ( ITV itv) {
this . itv = itv;
}
@Override
public void open ( ) {
this . itv. play ( ) ;
}
}
方案一
public class DependecyInversion {
public static void main ( String[ ] args) {
Person person = new Person ( ) ;
person. receive ( new Email ( ) ) ;
}
}
class Email {
public String getInfo ( ) {
return "电子邮件信息 Hello Word" ;
}
}
class Person {
public void receive ( Email email) {
System. out. println ( email. getInfo ( ) ) ;
}
}
方案二
public class DependecyInversion2 {
public static void main ( String[ ] args) {
Person person = new Person ( ) ;
person. receive ( new Email ( ) ) ;
person. receive ( new WeiXin ( ) ) ;
}
}
interface IReceiver {
String getInfo ( ) ;
}
class Email implements IReceiver {
@Override
public String getInfo ( ) {
return "电子邮件信息 Hello Word" ;
}
}
class WeiXin implements IReceiver {
@Override
public String getInfo ( ) {
return "微信信息 Hello Word" ;
}
}
class Person {
public void receive ( IReceiver iReceiver) {
System. out. println ( iReceiver. getInfo ( ) ) ;
}
}
依赖注入的注意事项和细节
1)低层模块尽量都要有抽象类或接口,或两者都有,程序稳定性更好
2)变量的声明类型尽量使抽象类或接口,这样我们的变量引用和实际对象间,就存在一个缓冲层,利于程序扩展和优化
3)继承时遵守里氏替换原则