先上基本概念,再谈谈我的理解:
适配器模式有两种,对象适配器和类适配器。
适配器模式将一个类的接口转换成客户期望的另一个接口,适配器让原本接口不兼容的类可以合作无间。
例子:交流电适配器。
看看类图关系:这个为对象适配器的类图
解释一下:
比如Client类有些方法A(),B();Adaptee也有一些特别的方法A1()和B1(),但是Client希望使用Adaptee中的方法,又不能直接使用,使用适配器模式怎么做呢?
一般是:
Adapter 实现Client所对应的接口,并将Adaptee作为一个对象成员定义在Adpter类中。然后实现AB方法,在AB方法中调用Adptee的A1B1方法。
比如接口为CInterface
那一般是
Adapter implement CInterfact{
Adaptee ae;
A()
{
ae.A1();
}
B()
{
ae.B1();
}
}
类适配器图:
interface ITarget
{
void Request();
}
class Adaptee
{
protected void SpecificRequest()
{
Console.WriteLine("Adaptee's SpecificRequest() method is calling");
}
}
class Adapter extends Adaptee implements ITarget
{
public void Request()
{
SpecificRequest();
}
}
class Client
{
static void Main(string[] args)
{
ITarget t new Adapter();
t.Request();
}
}