设计模式与实例代码:Adapter模式

来源:互联网 发布:淘宝上怎么找人帮代卖 编辑:程序博客网 时间:2024/06/06 08:50

定义/意图:将一个类的接口转换成客户希望的另外一个接口,使控制范围之外的一个原有类与我们期望的接口匹配。

问题:系统的数据和行为都正确,但接口不符:

解决方案:Adapter模式提供了具有所需要接口的包装类

参与者与协作者:Adapter改变了被适配类的接口,使得被适配类与Adapter的基类接口匹配。这样client就可以无分别的使用被适配的对象

效果:适配器模式使原有对象能够适应新的类结构,不受其接口限制

实现:将被适配类包含在Adapter类之中,Adapter与需要的接口匹配,调用其包含的类方法。


下面给出引模式的实现代码:

// Adapter pattern -- Structural exampleusing System; namespace Adapter{  /// <summary>  /// MainApp startup class for Structural  /// Adapter Design Pattern.  /// </summary>  class MainApp  {    /// <summary>    /// Entry point into console application.    /// </summary>    static void Main()    {      // Create adapter and place a request      Target target = new Adapter();      target.Request();       // Wait for user      Console.ReadKey();    }  }   /// <summary>  /// The 'Target' class  /// </summary>  class Target  {    public virtual void Request()    {      Console.WriteLine("Called Target Request()");    }  }   /// <summary>  /// The 'Adapter' class  /// </summary>  class Adapter : Target  {    private Adaptee _adaptee = new Adaptee();     public override void Request()    {      // Possibly do some other work      //  and then call SpecificRequest      _adaptee.SpecificRequest();    }  }   /// <summary>  /// The 'Adaptee' class  /// </summary>  class Adaptee  {    public void SpecificRequest()    {      Console.WriteLine("Called SpecificRequest()");    }  }}

在Head First设计模式中有一个把鸭子装扮成火鸡的例子。在这里不再赘述。

在使用中有时所适配的对象可能并不能完全完成所需要的功能,这种情况下我们仍可以使用Adapter模式,这样已有类中的功能可以适配,而没有的功能可以在包装类中实现。

实际上,Adapter模式有两种类型,对象适配器和类适配器。我们上面看的例子和是对象适配器,Adapter中包含了一个Adaptee的对象。

类适配器方式采用多重继承的方式来实现,在类图中唯一的变动就是由Adapter继承自Adaptee。




原创粉丝点击