您的位置:首页 > 其它

设计模式学习笔记之适配器模式

2009-02-11 16:14 295 查看
存在目地:将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
应用场合:由于应用环境的变化,常常需要将“一些现存的对象”放在新的环境中应用,但是新环境要求的接口是这些现存对象所不满足的。主要应用于“希望复用一些现存的类,但是接口又与复用环境要求不一致的情况”,在遗留代码复用、类库迁移等方面非常有用。
应用实例:ADO.NET为统一的数据访问提供了多个接口和基类,其中最重要的接口之一是IdataAdapter。与之相对应的DataAdpter是一个抽象类,它是ADO.NET与具体数据库操作之间的数据适配器的基类。DataAdpter起到了数据库到DataSet桥接器的作用,使应用程序的数据操作统一到DataSet上,而与具体的数据库类型无关。
生活中的例子,美国的生活用电电压是110V,而中国的电压是220V。如果要在中国使用美国电器,就必须有一个能把220V电压转换成110V电压的变压器。这个变压器就是一个Adapter。
实现方式:
类的适配器模式--采用“多继承”的实现方式,带来了不良的高耦合,一般不推荐使用
using System;
// 目标角色Target,客户所期待的接口
interface ITarget
{
// Methods
void Request();
}
// 源角色Adaptee,需要适配的类
class Adaptee
{
// Methods
public void SpecificRequest()
{
Console.WriteLine("Called SpecificRequest()" );
}
}
// 适配器Adapter,把源接口转换成目标接口。这一角色必须是类。
class Adapter : Adaptee, ITarget
{
// Implements ITarget interface
public void Request()
{
// Possibly do some data manipulation
// and then call SpecificRequest
this.SpecificRequest();
}
}
/**//// <summary>
/// Client test
/// </summary>
public class Client
{
public static void Main(string[] args)
{
// Create adapter and place a request
ITarget t = new Adapter();
t.Request();
}
}
用一个具体的Adapter类对Adaptee和Taget进行匹配,结果是当我们想要匹配一个类以及所有它的子类时,类Adapter将不能胜任工作。同时因为Adapter是Adaptee的一个子类,使得Adapter可以重定义Adaptee的部分行为。
对象适配器模式--采用“对象组合”的方式,更符合松耦合精神。
using System;
// 目标角色,客户所期待的接口,可以是具体的或抽象的类,也可以是接口
class Target
{
// Methods
virtual public void Request()
{
// Normal implementation goes here
}
}
// 源角色,需要适配的类
class Adaptee
{
// Methods
public void SpecificRequest()
{
Console.WriteLine("Called SpecificRequest()" );
}
}
// 适配器角色,在内部包装一个Adaptee对象,把源接口转换成目标接口
class Adapter : Target
{
// 创建一个需要适配的类的对象
private Adaptee adaptee = new Adaptee();
// Methods
override public void Request()
{
// Possibly do some data manipulation
// and then call SpecificRequest
adaptee.SpecificRequest();
}
}
/**//// <summary>
/// Client test
/// </summary>
public class Client
{
public static void Main(string[] args)
{
// Create adapter and place a request
Target t = new Adapter();
t.Request();
}
}
通过运用Adapter模式,就可以充分享受进行类库迁移、类库重用所带来的乐趣。

参考资料:

TerryLee's Tech Space
吕震宇博客
Erich Gamma《设计模式可复用面向对象软件的基础》
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: