Adapter -- 适配器模式: 将一个接口转换成客户希望的另一个接口, 使原本因为接口不兼容而不能在一起工作的两个类可以在一起工作。
特点: 兼容
代码上特点: 适配器与原来的类有不同的接口,并且实现了需要适配的类的实例
举例:
// 适配前接口
public interface A {
public void specificRequest(String s1, String s2);
}
// 需要适配的类
public class Adaptee implements A {
@Override
public void specificRequest(String s1, String s2) {
System.out.println(s1 + s2);
}
}
// 客户希望的接口
public interface Target {
public void request(String s1);
}
// 适配器类
public class Adapter implements Target {
A adaptee;
public Adapter() {
adaptee = new Adaptee();
}
// 源接口转换为目标接口
@Override
public void requst(String s1) {
adaptee.specificRequest(s1, "");
}
}
// 测试类
public class Test{
public static void main(Stirng[] args) {
Target target = new Target();
target.request("123321");
}
}