适配器模式(Adapter Pattern):将一个类的接口转换成客户所期待的另一个接口,使得原本由于接口不匹配而无法在一起工作的那些类能够在一起工作。
结构:(类的适配器模式)
(对象的适配器模式)
角色:
Target角色:这是客户所期待的接口。目标可以是具体的或抽象的类,也可以是接口。
Adaptee角色:需要适配的类。
Adapter角色:通过在内部包装一个Adaptee对象,把源接口转换成目标接口。
示例代码:
// 类适配器
using System;
// "ITarget"
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();
}
}
public class Client
{ public static void Main(string[] args)
{ // Create adapter and place a request
ITarget t = new Adapter();
t.Request();
}
}
// 对象适配器
using System;
// "Target"
class Target
{ virtual public void Request()
{ // Normal implementation goes here }
}
// "Adapter"
class Adapter : Target
{ // Fields
private Adaptee adaptee = new Adaptee();
// Methods
override public void Request()
{ // Possibly do some data manipulation
// and then call SpecificRequest
adaptee.SpecificRequest();
}
}
// "Adaptee"
class Adaptee
{ // Methods
public void SpecificRequest()
{ Console.WriteLine("Called SpecificRequest()" ); }
}
public class Client
{ public static void Main(string[] args)
{ // Create adapter and place a request
Target t = new Adapter();
t.Request();
}
}
Adapter模式的要点:
Adapter模式可以实现得非常灵活,不必拘泥于GoF的两种结构。例如,完全可以将Adapter模式中的“现存对象”作为新的接口方法参数,来达到适配的目的。
Adapter模式本身要求我们尽可能地使用“面向接口的编程”风格,这样才能在后期很方便地适配。