以上是适配器模式的示意图。客户端需要(只能)使用Target提供的接口,但是目前只存在Adaptee接口,因此需要一个适配器将接口进行转换。Adapter实现了Target接口,在Request()方法中调用了SpecificRequest(),这可以通过继承Adaptee或者持有Adaptee引用(组合)来实现。代码如下:
public interface Target {
void request();
}
public class Adaptee {
public void specificRequest(){
doSomething;
};
}
Adaptor通过组合来实现
public class Adaptor implements Target{
private Adaptee adaptee;
public void request() {
adaptee.specificRequest();
}
}
Adaptor也可以通过继承实现
public class Adaptor extends Adaptee implements Target{
public void request() {
specificRequest();
}
}
public class client {Target target = new Adaptor();//客户端只能够使用Target接口
target.request();//通过target调用request(),实际上调用了specificRequest(),Adaptor充当了中间人(转换)角色
}
原文:https://www.cnblogs.com/wangjq/archive/2012/07/09/2582485.html