如何在单个应用程序中封装对类似外部库的访问

本文关键字:外部 访问 封装 单个 应用程序 | 更新日期: 2023-09-27 18:16:10

我有一个应用程序,我们打算使用一个外部库。这个外部库是提供相同(或类似)功能的众多库之一。

以zip库为例,有很多库基本上做同样的事情,提取和压缩zip文件。

然而,即使内部压缩算法是相同的,每个库实现它们的公共类/接口也会彼此略有不同,例如
namespace AmazingZipLibrary
{
    public class Archive
    {
        public Zip Add()
        {
          //Create a zip file
        }
    }
}
namespace YetAnotherAmazingZipLibrary
{
    public class Zip
    {
        public object Compress()
        {
          //create a zip file
        }
    }
}

当我们想要交换或使用另一个库时,如何在不破坏主应用程序的情况下互换使用库?我认为这些需求的主要原因是为了评估和测试的目的。但是也有可能出现一个我们想要采用的新的糟糕的zip库(假设)。

什么设计模式可以帮助解决这种情况?

如何在单个应用程序中封装对类似外部库的访问

使用所需的方法创建自己的接口。

为每个库实现这个接口,用调用包装库功能。

interface ICompress
{
  void Create();
}
public class AmazingCompressor : ICompress
{
   public void Create()
   {
      // Call AmazingZipLibrary.Add
   }
}
public class YetAnotherAmazingCompressor : ICompress
{
   public void Create()
   {
      // Call YetAnotherAmazingZipLibrary.Compress
   }
}

在你的代码中,只引用ICompress

桥梁设计模式将是一个不错的选择。