前言

這篇開始前可以先搭配前面的介面、內聚、耦合一同觀看。

本文

介面隔離原則 Interface Segregation Principle(ISP)

最重要的精神:

不應該強迫用戶去依賴他們未使用的方法。
意及應該要最小化類別與類別之間的介面。

基本原則:

  • 1、interface 功能盡量少:達到一個介面只服務一個子模組/商業邏輯。 但有可能會與單一職責原則有衝突,比如已經拆成最仔細但功能還是很多,此時要以單一職責原則為優先。
  • 2、不應該強迫實作沒用到的方法。

舉例:今天我們有個車子的設計圖,我們可以用來設計車子,於是我們創造了特斯拉以及 Gogoro。

  1. public interface 車子
  2. {
  3. public string 引擎();
  4. public string 後照鏡();
  5. public string 車門();
  6. }
  7. public class 特斯拉 : 車子
  8. {
  9. public string 引擎()
  10. {
  11. return "3秒內時速100公里的引擎";
  12. }
  13. public string 後照鏡()
  14. {
  15. return "左右後視鏡+駕駛座後視鏡+電腦雷達感應周邊";
  16. }
  17. public string 車門()
  18. {
  19. return "側開敞篷車門";
  20. }
  21. }
  22. public class Gogoro : 車子
  23. {
  24. public string 引擎()
  25. {
  26. return "5秒內時速100公里的引擎";
  27. }
  28. public string 後照鏡()
  29. {
  30. return "左右後視鏡";
  31. }
  32. public string 車門()
  33. {
  34. return "痾沒有車門";
  35. }
  36. }
  37. private static void Main(string[] args)
  38. {
  39. var 特斯拉 = new 特斯拉();
  40. Console.WriteLine($"特斯拉有 : {特斯拉.引擎()}");
  41. Console.WriteLine($"特斯拉有 : {特斯拉.後照鏡()}");
  42. Console.WriteLine($"特斯拉有 : {特斯拉.車門()}");
  43. Console.WriteLine("=====================");
  44. var gogoro = new Gogoro();
  45. Console.WriteLine($"Gogoro有 : {gogoro.引擎()}");
  46. Console.WriteLine($"Gogoro有 : {gogoro.後照鏡()}");
  47. Console.WriteLine($"Gogoro有 : {gogoro.車門()}");
  48. }

這時候會發現我們設計稿並不適用於 Gogoro,思考一下特斯拉與 Gogoro 的種類,一種為電動車、一種為電動機車,兩者的配件也不同不可互用;所以我們應該拆分兩種不同的設計稿,程式修改如下。

  1. public interface 電動車
  2. {
  3. public string 電動車引擎();
  4. public string 電動車後照鏡();
  5. public string 電動車門();
  6. }
  7. public interface 電動機車
  8. {
  9. public string 電動機車引擎();
  10. public string 電動機車後照鏡();
  11. }
  12. public class 特斯拉 : 電動車
  13. {
  14. public string 電動車引擎()
  15. {
  16. return "3秒內時速100公里的引擎";
  17. }
  18. public string 電動車後照鏡()
  19. {
  20. return "左右後視鏡+駕駛座後視鏡+電腦雷達感應周邊";
  21. }
  22. public string 電動車門()
  23. {
  24. return "側開敞篷車門";
  25. }
  26. }
  27. public class Gogoro : 電動機車
  28. {
  29. public string 電動機車引擎()
  30. {
  31. return "5秒內時速100公里的引擎";
  32. }
  33. public string 電動機車後照鏡()
  34. {
  35. return "左右後視鏡";
  36. }
  37. }
  38. private static void Main(string[] args)
  39. {
  40. var 特斯拉 = new 特斯拉();
  41. Console.WriteLine($"特斯拉有 : {特斯拉.電動車引擎()}");
  42. Console.WriteLine($"特斯拉有 : {特斯拉.電動車後照鏡()}");
  43. Console.WriteLine($"特斯拉有 : {特斯拉.電動車門()}");
  44. Console.WriteLine("=====================");
  45. var gogoro = new Gogoro();
  46. Console.WriteLine($"Gogoro有 : {gogoro.電動機車引擎()}");
  47. Console.WriteLine($"Gogoro有 : {gogoro.電動機車後照鏡()}");
  48. }

參考連結