适配器模式(Adapter Pattern)是一种结构型设计模式,它能使接口不兼容的对象能够相互合作。
解释
适配器是一个特殊的对象,能够转换对象接口,使其能与其他对象进行交互。
适配器模式通过封装对象将复杂的转换过程隐藏于幕后。被封装的对象甚至察觉不到适配器的存在。

适配器模式 UML

适用场景
- 当你希望使用某个类,但是其接口与其他代码不兼容时,可以使用适配器类
 
- 如果您需要复用这样一些类,他们处于同一个继承体系,并且他们又有了额外的一些共同的方法,但是这些共同的方法不是所有在这一继承体系中的子类所具有的共性
 
代码示例
using System; namespace AdapterPatternDemo  {     public interface ITarget     {         string GetRequest();     }
      class Adaptee     {         public string GetSpecificRequest()         {             return "Specific request.";         }     }
      class Adapter : ITarget     {         private readonly Adaptee _adaptee;
          public Adapter(Adaptee adaptee)         {             _adaptee = adaptee;         }
          public string GetRequest()         {             return $"This is '{_adaptee.GetSpecificRequest()}'";         }     }
      class Program     {         static void Main(string[] args)         {             Adaptee adaptee = new Adaptee();             ITarget target = new Adapter(adaptee);
              Console.WriteLine("Adaptee interface is incompatible with the client.");             Console.WriteLine("But with adapter client can call it's method.");
              Console.WriteLine(target.GetRequest());             
                                                 }     } }
 
  |