问题代码
package com.pro.princle.inversion;
public class DependecyInversion {
public static void main(String[] args) {
Person person = new Person();
person.rercive(new Email());
}
}
class Person{
public void rercive(Email email) {
System.out.println(email.getInfo());
}
}
*/
class Email{
public String getInfo() {
return "电子邮件信息:hello world";
}
}
*/
改进
package com.pro.princle.inversion;
public class DependecyInversion1 {
public static void main(String[] args) {
Person person = new Person();
person.rercive(new Email());
person.rercive(new WeiXin());
}
}
interface IReceiver{
public String getInfo() ;
}
class Person {
public void rercive(IReceiver iReceiver) {
System.out.println(iReceiver.getInfo());
}
}
class Email implements IReceiver{
public String getInfo() {
return "电子邮件信息:hello world";
}
}
class WeiXin implements IReceiver{
public String getInfo() {
return "微信信息:hello world";
}
}
三种方式实现依赖倒转
- 通过接口传递实现依赖
- 通过构造方法依赖传递
- 通过setter方法传递
package com.pro.princle.inversion;
public class DependencyPass {
public static void main(String[] args) {
}
}
interface IOpenAndClose {
public void open();
public void setTv(ITV tv);
}
interface ITV {
public void play();
}
class OpenAndClose implements IOpenAndClose {
private ITV tv;
public void setTv(ITV tv) {
this.tv = tv;
}
public void open() {
this.tv.play();
}
}