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

1、Why

      在实际开发过程中,由于系统的升级需要对现有的系统进行改造,旧的代码可能就不兼容新的设计了。

      由于系统业务很复杂或部分业务数据在新系统试运行,不能直接在原有代码上进行修改....

      如何让老系统在几乎不改任何代码的基础上去兼容新的接口(标准接口)--适配器模式

2、How

     比如日志模块,

     老系统:

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

   新的设计,需要设计出一个标准,暂时用File去记录,或许以后会用NLog,RabbitMQ,新的日志服务就都要实现标准接口

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

    File记录:

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

   调用:

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

 

原文地址:https://www.cnblogs.com/zjflove/p/6831997.html