接口隔离原则 C.

这里我们举一个 ISP 违规的例子,然后重构那个违规行为。如果不谈论不必要的事情,让我们跳进代码。

ISP 违规:

public interface IMessage{
 IList<string> ToAddress {get; set;}
 IList<string> BccAddresses {get; set;}
 string MessageBody {get; set;}
 string Subject {get; set;}
 bool Send();
}
 
public class SmtpMessage : IMessage{
 public IList<string> ToAddress {get; set;}
 public IList<string> BccAddresses {get; set;}
 public string MessageBody {get; set;}
 public string Subject {get; set;}
 public bool Send(){
  // Code for sending E-mail.
 }
}
 
public class SmsMessage : IMessage{
 public IList<string> ToAddress {get; set;}
 public IList<string> BccAddresses {
  get { throw new NonImplementedException(); }
  set { throw new NonImplementedException(); } 
 }
 public string MessageBody {get; set;}
 public string Subject {
  get { throw new NonImplementedException(); }
  set { throw new NonImplementedException(); } 
 }
 public bool Send(){
  // Code for sending SMS.
 }
}

SmsMessage 我们不需要 BccAddresses 和主题,但我们被迫实行,因为它即时聊天界面。所以它违反了 ISP 的原则。

根据 ISP 删除违规行为 :

public interface IMessage{
 bool Send(IList<string> toAddress, string messageBody);
}
 
public interface IEmailMessage : IMessage{
 string Subject {get; set;}
 IList<string> BccAddresses {get; set;}
}
 
public class SmtpMessage : IEmailMessage{
 public IList<string> BccAddresses {get; set;}
 public string Subject {get; set;}
 public bool Send (IList<string> toAddress, string messageBody){
  // Code for sending E-mail.
 }
}
 
public class SmsMessage : IMessage{
 public bool Send (IList<string> toAddress, string messageBody){
  // Code for sending SMS.
 }
}

SmsMessage 只需要的 toAddress消息体,所以现在我们可以使用即时聊天界面,以避免不必要的实现。