适配器模式:改变遗留对象的抽象(接口),以匹配当前的环境,使得其能够正常的工作
优点:可以让两个没有任何关联的对象匹配在一起运行,而对用调用者来说是透明的,适配器是一种补救措施,在设计阶段一般不考虑。
标准类图:
目标接口:
public interface TargetInterface {
void targetMethod();
}
目标实现:
public class Target implements TargetInterface{
@Override
public void targetMethod() {
System.out.println("target's method");
}
}
被适配的类:
public class Adaptee {
public void doAdapteeMethod(){
System.out.println("do adaptee method");
}
}
适配器类:
public class Adapter extends Adaptee implements TargetInterface{
@Override
public void targetMethod() {
super.doAdapteeMethod();
}
}
场景类:
public class Client {
public static void main(String[] args) {
TargetInterface target = new Target();
target.targetMethod();
TargetInterface adapter = new Adapter();
adapter.targetMethod();
}
}
上述模式为类适配器模式,因为适配器类是采用继承的方式实现适配,如果换成关联关系方式实现则成为对象适配器模式(关联关系实现适配具有更高的灵活性):
public class Adapter implements TargetInterface {
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public void targetMethod() {
adaptee.doAdapteeMethod();
}
}