1 / 11
文档名称:

适配器(Adapter)模式.doc

格式:doc   大小:160KB   页数:11页
下载后只包含 1 个 DOC 格式的文档,没有任何的图纸或源代码,查看文件列表

如果您已付费下载过本站文档,您可以点这里二次下载

分享

预览

适配器(Adapter)模式.doc

上传人:sanshenglu2 2020/12/19 文件大小:160 KB

下载得到文件列表

适配器(Adapter)模式.doc

相关文档

文档介绍

文档介绍:C#设计模式(10)-Adapter Pattern
结构模式(Structural Pattern)描述如何将类或者对象结合在一起形成更大的结构。结构模式描述两种不同的东西:类与类的实例。根据这一点,结构模式可以分为类的结构模式和对象的结构模式。
后续内容将包括以下结构模式:
适配器模式(Adapter):Match interfaces of different classes
合成模式(Composite):A tree structure of simple and composite objects
装饰模式(Decorator):Add responsibilities to objects dynamically
代理模式(Proxy):An object representing another object
享元模式(Flyweight):A fine-grained instance used for efficient sharing
门面模式(Facade):A single class that represents an entire subsystem
桥梁模式(Bridge):Separates an object interface from its implementation
一、 适配器(Adapter)模式
适配器模式把一个类的接口变换成客户端所期待的另一种接口,从而使原本接口不匹配而无法在一起工作的两个类能够在一起工作。
名称由来
这很像变压器(Adapter),变压器把一种电压变换成另一种电压。美国的生活用电电压是110V,而中国的电压是220V。如果要在中国使用美国电器,就必须有一个能把220V电压转换成110V电压的变压器。这个变压器就是一个Adapter。
Adapter模式也很像货物的包装过程:被包装的货物的真实样子被包装所掩盖和改变,因此有人把这种模式叫做包装(Wrapper)模式。事实上,大家经常写很多这样的Wrapper类,把已有的一些类包装起来,使之有能满足需要的接口。
适配器模式的两种形式
适配器模式有类的适配器模式和对象的适配器模式两种。我们将分别讨论这两种Adapter模式。
二、 类的Adapter模式的结构:
 
由图中可以看出,Adaptee类没有Request方法,而客户期待这个方法。为了使客户能够使用Adaptee类,提供一个中间环节,即类Adapter类,Adapter类实现了Target接口,并继承自Adaptee,Adapter类的Request方法重新封装了Adaptee的SpecificRequest方法,实现了适配的目的。
因为Adapter与Adaptee是继承的关系,所以这决定了这个适配器模式是类的。
该适配器模式所涉及的角色包括:
目标(Target)角色:这是客户所期待的接口。因为C#不支持多继承,所以Target必须是接口,不可以是类。
源(Adaptee)角色:需要适配的类。
适配器(Adapter)角色:把源接口转换成目标接口。这一角色必须是类。
三、 类的Adapter模式示意性实现:
下面的程序给出了一个类的Adapter模式的示意性的实现:
//  Class Adapter pattern -- Structural example  
using System;
// "ITarget"
interface ITarget
{
  // Methods
  void Request();
}
// "Adaptee"
class Adaptee
{
  // Methods
  public void SpecificRequest()
  {
    ("Called SpecificRequest()" );
  }
}
// "Adapter"
class Adapter : Adaptee, ITarget
{
  // Implements ITarget interface
  public void Request()
  {
    // Possibly do some data manipulation
    // and then call SpecificRequest
    ();
  }
}
public class Client
{
  public static void Main(string[] args)
  {
    // Create