【问题标题】:Why use Adapter design pattern为什么使用适配器设计模式
【发布时间】:2019-06-26 16:08:29
【问题描述】:

所以我正在研究适配器设计模式。我看到这样做的目的是允许客户端访问它们的接口不兼容的类的方法。

现在我一直在看this example

interface ITarget
{
  List<string> GetProducts();
}


public class VendorAdaptee
{
   public List<string> GetListOfProducts()
   {
      List<string> products = new List<string>();
      products.Add("Gaming Consoles");
      products.Add("Television");
      products.Add("Books");
      products.Add("Musical Instruments");
      return products;
   }
}

class VendorAdapter:ITarget
{
   public List<string> GetProducts()
   {
      VendorAdaptee adaptee = new VendorAdaptee();
      return adaptee.GetListOfProducts();
   }
}

class ShoppingPortalClient
{
   static void Main(string[] args)
   {
      ITarget adapter = new  VendorAdapter();
      foreach (string product in adapter.GetProducts())
      {
        Console.WriteLine(product);
      }
      Console.ReadLine();
   }
}

所以根据描述 ShoppingPortalClient 想使用 VendorAdaptee 但由于接口不兼容而无法使用。这是我的愚蠢问题……为什么 ShoppingPortalClient 不能这样做:

var adaptee = new VendorAdaptee();

【问题讨论】:

标签: design-patterns


【解决方案1】:

ShoppingPortalClient 不能直接使用适配器,因为适配器的接口不是 ITarget(它所期望的)。换句话说,VendorAdaptee 没有有一个GetProducts() 方法,它有一个GetListOfProducts() 方法。这些是不同的接口。这不适用于ShoppingPortalClient 使用的现有库存管理系统。

【讨论】:

  • 感谢您的回复。我不太确定我是否同意这一点,因为我相信 ITarget 是作为整个适配器设计模式的一部分创建的。因此,如果您只有 MainVendorAdaptee,为什么我们不能只新建 VendoreAdaptee。
  • 不,这不正确。 ITarget 存在是因为客户端依赖它,而不是因为适配器需要它。适配器需要它只是因为客户端需要它,这是使用适配器的全部意义所在,也是这种模式存在的原因。
  • 客户端需要一个接口。适配者有一个完全不同的接口。适配器将两者连接起来。您发布的文章的作者甚至将适配器 in Main 键入为ITarget adapter
  • 来自发表的文章:“ITarget:这是客户端使用实现功能的接口。”
  • 感谢 Reafael。是的,在你的评论之后,我重新阅读了它,现在它是有道理的。因此,正如您提到的,ITarget 是客户所依赖的。谢谢。干杯。
【解决方案2】:

这个例子没有任何意义。没有理由在ShoppingPortalClient 中使用适配器,因为该类不需要使用ITarget 接口。

如果它必须在某处传递ITarget,例如,如果它必须在不同的类中调用performSomeOperation(ITarget)那么创建一个适配器来传递是有意义的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-16
    • 1970-01-01
    • 2012-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多