高级模块不应依赖于低级模块。两者都应该依赖抽象,抽象不应该依赖细节。细节应取决于抽象。此原则主要涉及减少代码模块之间的依赖性。
依赖反转之前的代码
using System; namespace SolidPrinciples.Dependency.Invertion.Before{ public class Email{ public string ToAddress { get; set; } public string Subject { get; set; } public string Content { get; set; } public void SendEmail(){ //发电子邮件 } } public class SMS{ public string PhoneNumber { get; set; } public string Message { get; set; } public void SendSMS(){ //发送短信 } } public class Notification{ private Email _email; private SMS _sms; public Notification(){ _email = new Email(); _sms = new SMS(); } public void Send(){ _email.SendEmail(); _sms.SendSMS(); } } }
依赖反转后的代码
using System.Collections.Generic; namespace SolidPrinciples.Dependency.Invertion.Before{ public interface IMessage{ void SendMessage(); } public class Email: IMessage{ public string ToAddress { get; set; } public string Subject { get; set; } public string Content { get; set; } public void SendMessage(){ //发电子邮件 } } public class SMS: IMessage{ public string PhoneNumber { get; set; } public string Message { get; set; } public void SendMessage(){ //发送短信 } } public class Notification{ private ICollection<IMessage> _messages; public Notification(ICollection<IMessage> messages){ this._messages = messages; } public void Send(){ foreach (var message in _messages){ message.SendMessage(); } } } }