Chinaunix首页 | 论坛 | 博客
  • 博客访问: 667494
  • 博文数量: 220
  • 博客积分: 10487
  • 博客等级: 上将
  • 技术积分: 2072
  • 用 户 组: 普通用户
  • 注册时间: 2009-08-09 00:25
文章分类

全部博文(220)

文章存档

2012年(5)

2011年(38)

2010年(135)

2009年(42)

我的朋友

分类:

2010-02-28 22:09:29

定义

把类的接口转换成客户端期望的另外的接口。适配器解决因接口的不兼容导致类不能协作的问题。

使用频度: 中高


UML类图



参与者

该模式参与的类或对象

  • Target
    • 定义客户使用的指定领域的接口
  • Adapter(适配器)
    • 转换Adaptee接口,使其能适应Target接口
  • Adaptee
    • 定义需要转换的已存在的接口
  • Client
    • 与实现Target接口的对象进行交互



C#示例代码

// Adapter pattern -- Structural example



using System;

 

namespace DoFactory.GangOfFour.Adapter.Structural

{

  ///




  /// MainApp startup class for Structural


  /// Adapter Design Pattern.


  ///



  class MainApp

  {

    ///


    /// Entry point into console application.


    ///



    static void Main()

    {

      // Create adapter and place a request


      Target target = new Adapter();

      target.Request();

 

      // Wait for user


      Console.ReadKey();

    }

  }

 

  ///


  /// The 'Target' class


  ///



  class Target

  {

    public virtual void Request()

    {

      Console.WriteLine("Called Target Request()");

    }

  }

 

  ///


  /// The 'Adapter' class


  ///



  class Adapter : Target

  {

    private Adaptee _adaptee = new Adaptee();

 

    public override void Request()

    {

      // Possibly do some other work


      // and then call SpecificRequest


      _adaptee.SpecificRequest();

    }

  }

 

  ///


  /// The 'Adaptee' class


  ///



  class Adaptee

  {

    public void SpecificRequest()

    {

      Console.WriteLine("Called SpecificRequest()");

    }

  }

}


输出

Called SpecificRequest()


阅读(872) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~