介面隔離原則 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訊息體,所以現在我們可以使用即時聊天介面,以避免不必要的實現。