适配器模式:把一个类的接口变换成客户端所期待的另一种接口,从而使原本接口不匹配而无法在一起工作的两个类能够在一起工作。

类的 Adapter模式的结构:

类适配器类图:

七、适配器(Adapter)模式--结构模式(Structural Pattern)

由图中可以看出,Adaptee 类没有 Request方法,而客户期待这个方法。为了使客户能够使用 Adaptee 类,提供一个中间环节,即类Adapter类,

Adapter 类实现了 Target 接口,并继承 自 Adaptee,Adapter 类的 Request 方法重新封装了Adaptee 的SpecificRequest方法, 实现了适配的目的。
因为 Adapter 与 Adaptee 是继承的关系,所以这决定了这个适配器模式是类的。


该适配器模式所涉及的角色包括:
  目标(Target)角色:这是客户所期待的接口。因为 C#不支持多继承,所以 Target 必须是接 口,不可以是类。

  源(Adaptee)角色:需要适配的类。

   适配器(Adapter)角色:把源接口转换成目标接口。这一角色必须是类。

示例代码:

class Program
    {
        static void Main(string[] args)
        {
            ITarget t = new Adapter();
            t.Request();
            Console.ReadKey();
        }
    }

    interface ITarget
    {
        void Request();
    }

    class Adaptee
    {
        public void SpecificRequest()
        {
            Console.WriteLine(" Call SpecificRequest();");
        }
    }

    class Adapter : Adaptee, ITarget
    {
        public void Request()
        {
            this.SpecificRequest();
        }
    }
View Code

相关文章: