31

我正在尝试了解适配器模式及其在现实世界中的使用。在浏览了互联网和 www.dofactory.com 上的各种文章后,我创建了这个示例代码。我只想知道我的理解是否正确。在下面的示例中,我在 Adapter 类中创建了 MSDAO 对象。后来我把它改成了OracleDAO。

class Client
{
  static void Main(string[] args)
  {
    ITarget objAdapter = new Adapter();
    object dummyObject = objAdapter.GetData();
  }
}

Interface ITarget
{
  public void GetData();
}

//Decision to use MSDAO

class Adapter : ITarget
{
  public void GetData()
  {
    MSDAO objmsdao = new MSDAO();
    objmsdao.GetData();
  }
}

//After a month, the decision to use OracaleDAO was taken, so the code change

class Adapter : ITarget
{
  public void GetData()
  {
    OracleDAO objoracledao = new OracleDAO();
    objoracledao.GetData();
  }
}
4

5 回答 5

86

通常适配器模式将一个接口转换为另一个接口,但它可以简单地包装行为以将您的类与底层实现隔离。在您的情况下,您使用的是适配器,但您可以轻松地定义 DAO 对象以简单地实现接口并针对接口进行编程。当您无法控制目标类时,通常使用适配器模式。我对适配器模式的主要用途是为不实现接口的框架类创建包装器。

假设我想模拟一个没有实现接口(并且没有虚拟方法)的框架类。对于许多模拟 api,这很难或不可能做到。那么,我要做的就是将我自己的接口定义为我所针对的类的签名的一个子集。我实现了一个实现此接口的包装类,并简单地将调用委托给包装的框架类。这个包装类用作框架类的适配器。我的类使用此适配器而不是框架类,但获取框架类的行为。

 public interface IFoo
 {
     void Bar();
 }

 public class FooWrapper : IFoo
 {
      private FrameworkFoo Foo { get; set; }

      public FooWrapper( FrameworkFoo foo )
      {
           this.Foo = foo;
      }

      public void Bar()
      {
           this.Foo.Bar();
      }
 }

还要考虑这样一种情况,即您有几个不同的类,它们具有基本相同的功能,但签名不同,并且您希望能够互换使用它们。如果您不能转换这些(或由于其他原因不想转换),您可能需要编写一个适配器类,该类定义一个通用接口并在该接口的方法和目标类上可用的方法之间进行转换。

框架类:

public class TargetA
{
    public void Start() { ... }
    public void End() { ... }
}

public class TargetB
{
    public void Begin() { ... }
    public void Terminate() { ... }
}

他们的适配器

public interface ITargetAdapter
{
    void Open();
    void Close();
}

public class AdapterA : ITargetAdapter
{
     private TargetA A { get; set; }

     public AdapterA( TargetA a )
     {
           this.A = a;
     }

     public void Open() { this.A.Start(); }
     public void Close() { this.A.End(); }
}

public class AdapterB : ITargetAdapter
{
     private TargetB B { get; set; }

     public AdapterB( TargetB a )
     {
           this.B = a;
     }

     public void Open() { this.B.Begin(); }
     public void Close() { this.B.Terminate(); }
}

然后用作:

ITargetAdapter adapter = new AdapterA( new TargetA() );
adapter.Open();
adapter.Close();     
于 2009-08-19T11:10:10.667 回答
3

.NET 框架内的一个规范示例存在于System.Drawing.Bitmap该类中。

此位图有一个构造函数,可让您从以下位置加载图像Stream

public Bitmap(
    Stream stream
)

你不知道的是,.NETBitmap类在内部是 GDI+Bitmap类的包装器,它的构造函数采用IStream

Bitmap(
  [in]  IStream *stream,
  [in]  BOOL useIcm
);

所以在 C# 世界中,当我调用时:

new Bitmap(stream);

它必须转身打电话:

IStream stm;
IntPtr gpBitmap;
GdipCreateBitmapFromStream(stm, out gpBitmap);

问题是如何将 .NET Stream对象呈现给需要 COM IStream接口的方法。

因此内部GPStream类:

internal class GPStream : IStream
{
   GPStream(Stream stream) { ... }
}

您需要为您的对象提供一个IStream接口:Stream

IStream                                     Stream
=======================================     =====================================
int Read(IntPtr buf, int len);          --> int Read(byte[] buffer, int offset, int count)
int Write(IntPtr buf, int len);         --> void Write(byte[] buffer, int offset, int count);
long Seek(long dlibMove, int dwOrigin); --> long Seek(long offset, SeekOrigin orgin)
...                                         ...

所以现在你有一个适配器:

在此处输入图像描述

代码类似于:

IStream stm = new GPStream(stream); //adapter to convert Stream --> IStream
IntPtr gpBitmap;

GdipCreateBitmapFromStream(stm, out gpBitmap);
于 2017-07-11T15:45:35.523 回答
3

我添加了一些评论,希望能帮助您了解整个适配器/适配器/客户端/Itarget 行话 - 这有点令人困惑:

internal class Program
{
    private static void Main(string[] args)
    {
        // Brian and freddie know only how to say Greetings. But when they tour
        // internationally, they will need a translator so when they say Greetings()
        // the appropriate non-English response comes out of their mouth.
        // they need to make use of the adapter pattern:

        // When in Japan:
        ITarget translator = new JapaneseTranslator(new JapaneseSpeaker());
        EnglishMan freddie = new EnglishMan(translator);

        // Freddie greets Tokyo, though he doesn't know a word of Japanese
        Console.WriteLine(freddie.Greetings()); //  "teo torriatte!"

        // when in France:
        ITarget translator2 = new FrenchTranslator(new FrenchSpeaker());
        EnglishMan brian = new EnglishMan(translator2);

        // Brian greets the crowd in Paris, though he doesn't know a word in French
        Console.WriteLine(brian.Greetings()); 
          // "So très charmant my dear! Bonjour"

        // alternatively, the translators can also do the greeting:
        Console.WriteLine(translator.Greetings());  //  "Konichiwa, hisashiburi!"
        Console.WriteLine(translator2.Greetings()); // "Bonjour!"
    }

    /// <summary>
    /// This is the client.
    /// </summary>
    public class EnglishMan : ITarget
    {
        private ITarget target;

        public EnglishMan(ITarget target)
        {
            this.target = target;
        }

        public string Greetings()
        {
            return target.Greetings();
        }
    }

    /// <summary>
    /// The target interface
    /// </summary>
    public interface ITarget
    {
        string Greetings();
    }

    /// <summary>
    /// This is the adaptor
    /// </summary>
    public class JapaneseTranslator : ITarget
    {
        private JapaneseSpeaker japanese;

        public JapaneseTranslator(JapaneseSpeaker japanese)
        {
            this.japanese = japanese;
        }

        public string Greetings()
        {
            return japanese.Konnichiwa();
        }
    }

    /// <summary>
    /// This is the adaptee
    /// </summary>
    public class JapaneseSpeaker
    {
        public JapaneseSpeaker()
        {
        }

        public string Konnichiwa()
        {
            return "Konichiwa, hisashiburi!";
        }
    }

    /// <summary>
    /// This is the adaptor
    /// </summary>
    public class FrenchTranslator : ITarget
    {
        private FrenchSpeaker french;

        public FrenchTranslator(FrenchSpeaker french)
        {
            this.french = french;
        }

        public string Greetings()
        {
            return french.Bonjour();
        }
    }

    /// <summary>
    /// This is the adaptee
    /// </summary>
    public class FrenchSpeaker
    {
        public string Bonjour()
        {
            return "Bonjour!!";
        }
    }
}
于 2017-09-28T11:42:23.270 回答
0

一个非常简单的例子...

 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();
       }
    }
于 2019-09-17T05:29:34.080 回答
0

我会保持非常简单。如果一个调用者想要调用 的GetData方法MSDAO而其他调用者想要OracleDAO. 或者将来也可以添加其他类。

在这种情况下,您的解决方案将不起作用。

所以我建议将该GetData方法声明为virtual适配器类。添加一个新的适配器类,扩展适配器类并实现您的ITarget接口并相应地实现GetData(声明它override)方法。

如果您将来有新课程,请重复上述步骤。

于 2022-01-28T20:44:05.980 回答