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 ..."); } }