依赖注入

github https://github.com/spring2go/core-spring-patterns.git

依赖倒置原则 (Dependency Inversion Principle)

  • SOLID面向对象原理之一
    • 高层模块不应该依赖底层模块。两者都应该依赖于抽象
    • 抽象不应该依赖于细节。细节应该依赖于抽象。
  • 总结:就是面向接口编程

只要接口不变,就可以任意更换设备

  1. 主机就是高层模块,剥露很多接口,接口就是抽象
  2. 接口不依赖于设备,设备依赖于接口,不依赖于主机。

问题:高层模块依赖于底层模块,不利于扩展,如果扩展需要修改代码
  1. 如果止时,不发送日志了,需要发送短信,此时就需要修改代码
// 高层模块
public class AppMonitorNoDIP {

	// 负责将事件日志写到日志系统
	private EventLogWriter writer = null;
	
	// 应用有问题时该方法将被调用
	public void notify(String message) {
		if (writer == null) {
			writer = new EventLogWriter();
		}
		writer.write(message);
	}
	
	public static void main(String[] args) {
		AppMonitorNoDIP appMonitor = new AppMonitorNoDIP();
		appMonitor.notify("App has a problem ...");
	}
}

// 底层模块
class EventLogWriter {
	public void write(String message) {
		// 写到事件日志
		System.out.println("Write to event log, message : " + message);
	}
}

使用依赖倒置原则改进 关系图

  • 高层模块不应该依赖底层模块。两者都应该依赖于抽象。
  • 抽象不应该依赖于细节。细节应该依赖于抽象。
// 事件通知器接口
public interface INotifier {
	public void notify(String message);
}

// 发送短消息
public class SMSSender implements INotifier {
	public void notify(String message) {
		System.out.println("Send SMS, message : " + message);
	}
}

// 写到事件日志
public class EventLogWriter implements INotifier {
	public void notify(String message) {
		System.out.println("Write to event log, message : " + message);
	}
}

// 发送Email
public class EmailSender implements INotifier {
	public void notify(String message) {
		System.out.println("Send email, message : " + message);
	}
}

依赖倒置DIP 客户端调用

  • 高层模块不依赖于底层接口,依赖于抽象
public class AppMonitorIOC {
	// 事件通知器
	private INotifier notifier = null;
	
	// 应用有问题时该方法被调用
	public void notify(String message) {
		if (notifier == null) {
			// 将抽象接口映射到具体类
			notifier = new EventLogWriter(); (这里有耦合性,需要new出来)
		}
		notifier.notify(message);
	}
	
	public static void main(String[] args) {
		AppMonitorIOC appMonitor = new AppMonitorIOC();
		appMonitor.notify("App has a problem ...");
	}
}

控制反转( Inversion of Control)

  1. 传统做法: 主程序的依赖和装配都是由主程序驱动的
  2. 依赖注入做法:当需要依赖对象时,由依赖注入器运行期注入进来

依赖注入(Dependency Injection)具体实现

  • 构造函数注入
  • Setter注入
  • 接口注入

构造函数注入

public class AppMonitorConstructorInjection {
	// 事件通知器
	private INotifier notifier = null;
	
	public AppMonitorConstructorInjection(INotifier notifier) {
		this.notifier = notifier;
	}
	
	// 应用有问题时该方法被调用
	public void notify(String message) {
		notifier.notify(message);
	}
	
	public static void main(String[] args) {
		EventLogWriter writer = new EventLogWriter();
		AppMonitorConstructorInjection monitor = 
				new AppMonitorConstructorInjection(writer);
		monitor.notify("App has a problem ...");
	}
	
}

spring ioc 依赖注入

  1. 定义元数据运行时的依赖关系
  2. spring ioc 在运行期,将需要的依赖注入进来

好处

  • 依赖解耦
    • 模块化:不只直接new
    • 易于测试
    • 易于变化和扩展
posted @ 2018-06-06 23:56  张建斌  阅读(282)  评论(0编辑  收藏  举报