適配器模式,新老系統兼容

一、Whyspa

      在實際開發過程當中,因爲系統的升級須要對現有的系統進行改造,舊的代碼可能就不兼容新的設計了。設計

      因爲系統業務很複雜或部分業務數據在新系統試運行,不能直接在原有代碼上進行修改....日誌

      如何讓老系統在幾乎不改任何代碼的基礎上去兼容新的接口(標準接口)--適配器模式code

 

二、Howblog

     好比日誌模塊,接口

     老系統:開發

    /// <summary>
    /// 老的系統記錄日誌的方式
    /// </summary>
    public class DbLog
    {
        public void Log(string content)
        {
            Console.WriteLine("write db log:{0}",content);
        }
    }

 

   新的設計,須要設計出一個標準,暫時用File去記錄,或許之後會用NLog,RabbitMQ,新的日誌服務就都要實現標準接口string

    /// <summary>
    /// 新的接口--標準
    /// </summary>
    public interface ILogService
    {
        void Log(string content);
    }

    File記錄:it

  /// <summary>
    /// 新接口的File實現
    /// </summary>
    public class FileLog : ILogService
    {
        public void Log(string content)
        {
            Console.WriteLine("write file log:{0}",content);
        }
    }

   調用:class

   string content="xxxxx";
   ILogService logService = new FileLog();
   logService.Log(content);

  讓老系統DbLog兼容新的接口

   /// <summary>
    /// 兼顧老的系統
    /// </summary>
    public class LogAdapter:ILogService
    {
        DbLog dbLog = new DbLog();
        public void Log(string content)
        { 
            dbLog.Log(content);
        }
    }

 

 調用:

           string content="xxxxx";
            ILogService logService = new FileLog();
            logService.Log(content);

            logService = new LogAdapter();
            logService.Log(content);

 

 

相關文章
相關標籤/搜索