您的位置:首页 > 编程语言 > C#

C#设计模式(10)-Adapter Pattern

2006-08-28 14:59 309 查看
结构模式(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模式的结构:

// Class Adapter pattern -- Structural example
using System;

// "ITarget"
interface ITarget

// "Adaptee"
class Adaptee

// "Adapter"
class Adapter : Adaptee, ITarget

public class Client
// Adapter pattern -- Structural example
using System;

// "Target"
class Target

// "Adapter"
class Adapter : Target

// "Adaptee"
class Adaptee

public class Client
// Example of implementing the Adapter pattern
using System;

// Target
public interface ICar

// Direct use without Adapter
public class CToyota : ICar

// Adaptee
public class CCessna

// Class Adapter
public class CDrivableCessna : CCessna, ICar

// Object Adapter
public class CDrivableCessna2 : ICar

// Client
public class Client
public static void Main(string[] args)
ICar oCar = new CToyota();

Console.Write("Class Adapter: Driving an Automobile oCar.Drive();
oCar = new CDrivableCessna();
Console.Write("Driving a Cessna oCar.Drive();
oCar = new CDrivableCessna2();
Console.Write(" Object Adapter: Driving a Cessna oCar.Drive();
}
}


八、 关于Adapter模式的讨论

Adapter模式在实现时有以下这些值得注意的地方:

1、 目标接口可以省略,模式发生退化。但这种做法看似平庸而并不平庸,它可以使Adaptee不必实现不需要的方法(可以参考Default Adapter模式)。其表现形式就是父类实现缺省方法,而子类只需实现自己独特的方法。这有些像模板(Template)模式。
2、 适配器类可以是抽象类。
3、 带参数的适配器模式。使用这种办法,适配器类可以根据参数返还一个合适的实例给客户端。

 

参考文献:
阎宏,《Java与模式》,电子工业出版社
[美]James W. Cooper,《C#设计模式》,电子工业出版社
[美]Alan Shalloway James R. Trott,《Design Patterns Explained》,中国电力出版社
[美]Robert C. Martin,《敏捷软件开发-原则、模式与实践》,清华大学出版社
[美]Don Box, Chris Sells,《.NET本质论 第1卷:公共语言运行库》,中国电力出版社
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: