依赖倒转原则

在这里插入图片描述

问题代码

/**
 * 
 */
package com.pro.princle.inversion;

/**
 * @author kans
 *
 */
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());
	}
}
*/

/* 完成Person功能
 * 1.简单易于实现
 * 2.入果我们获取的对象是微信,短信等,新增加类时,person也要增加对应的接受方法
 * 3.解决方案:引入一个接口IRecevier,表示接受者,这样person类就与接口IRecervice发生依赖
 * 	因为email,weixin 等等属于接受范围,他们各自实现了IRecevier接口就可以实现对应功能,这样就符合依赖倒转原则
 * 
 */
class Email{
	public String getInfo() {
		return "电子邮件信息:hello world";
	}
}
*/

改进

/**
 * 
 */
package com.pro.princle.inversion;

/**
 * @author kans
 *
 */
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) {

	}

}

// 方式1: 通过接口传递实现依赖
// 开关的接口
// interface IOpenAndClose {
// public void open(ITV tv); //抽象方法,接收接口
// }
//
// interface ITV { //ITV接口
// public void play();
// }
 实现接口
// class OpenAndClose implements IOpenAndClose{
// public void open(ITV tv){
// tv.play();
// }
// }

// 方式2: 通过构造方法依赖传递
// interface IOpenAndClose {
// public void open(); //抽象方法
// }
// interface ITV { //ITV接口
// public void play();
// }
// class OpenAndClose implements IOpenAndClose{
// public ITV tv;
// public OpenAndClose(ITV tv){
// this.tv = tv;
// }
// public void open(){
// this.tv.play();
// }
// }

// 方式3 , 通过setter方法传递
interface IOpenAndClose {
	public void open(); // 抽象方法

	public void setTv(ITV tv);
}

interface ITV { // 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();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值