适配器的定义是:
把一个类的接口转换成客户想要的另一个接口。让多个不兼容接口的类能够协作。
其UML类图的示例如下:
在这个模式中,参与者包括:
- Target:定义Client要用到的特定领域的接口。
- Adapter:把Adaptee接口适配到Target接口上。
- Adaptee:定义一个现存的需要适配的接口。
- Client:把符合Target接口的对象协作起来。
实现代码:
public class Client
{
private ITarget target;
public Client(ITarget target)
{
this.target = target;
}
public void MakeRequest()
{
target.MethodA();
}
}
public interface ITarget
{
void MethodA();
}
public class Adapter : Adaptee, ITarget
{
public void MethodA()
{
MethodB();
}
}
public class Adaptee
{
public void MethodB()
{
Console.WriteLine("MethodB() is called");
}
}
- 允许系统使用另一个系统中不兼容的类。
- 允许相对独立的新系统和老系统之间相互通信。
- Ado.Net SqlAdapter, OracleAdapter, MySqlAdapter都是很好的例子。