2017年1月2日 星期一

設計模式 AdpaterPattern 轉接器模式

情境:
目前已經有讀取資料的類別了
要設計一個讀取資料類別支援 Json 格式

1.目前已經有一個讀取資料的方法了

  1. public class FileReader
  2. {
  3. public string Read(string parameter)
  4. {
  5. string result = string.Empty;
  6. //實作硬碟讀取
  7. return result;
  8. }
  9. }
  10.  
  11.  

2.設計一個讀取資料的介面

  1. public interface IReadData
  2. {
  3. string GetJsonData(string parameter);
  4. }
  5.  
  6.  

3.繼承這個 IReadData 介面
  1. ///
  2. /// 從網路上讀取要的資料
  3. ///
  4. public class WebReader : IReadData
  5. {
  6. public string GetJsonData(string parameter)
  7. {
  8. string result = string.Empty;
  9. //實作網路讀取
  10. return result;
  11. }
  12. }
  13.  
  14.  

4.要讓 FileReader 共享 IReadData 介面 這時候轉接器模式就可以上場了
  1. public class FileAdapter : IReadData
  2. {
  3. public string GetJsonData(string parameter)
  4. {
  5. var reader = new FileReader();
  6. return reader.Read(parameter);
  7. }
  8. }
  9.  
  10.  

總結:
雖然 FileReader 在 FileAdapter 內
但是外部看起來 WebReader 與 FileAdapter 同樣繼承 IReadData 介面

沒有留言:

Visual Studio 2017/2019 推薦的擴充功能與更新

參考文章: 覺得 Google 的 Blogger 不太順手?透過 HTML 的 iframe 移花接木 HackMD