github https://github.com/spring2go/core-spring-patterns.gitgit
// 高层模块 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); } }
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 ..."); } }
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 ..."); } }