适配器模式,新老系统兼容

一、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);

 

 

相关文章
相关标签/搜索