定义:适配器模式将一个类的接口,转换成客户期望的另一个类的接口,适配器让原本接口不兼容的类可以合作无间(headfirst设计模式)
代码块
接口A
public interface A {
void a();
}
接口B
public interface B {
void b();
}
B的实现类
public class BImpl implements B {
@Override
public void b() {
System.out.println("执行实现B接口类的b方法");
}
}
适配器BAdapter,实现A接口
public class BAdapter implements A {
B b;
public BAdapter(B b) {
this.b = b;
}
@Override
public void a() {
System.out.println("我是B接口的适配器,我实现了A接口,执行实现A接口类的a方法");
b.b();
}
}
测试类
public class Test {
public static void main(String[] args) {
B b = new BImpl();
BAdapter bAdapter = new BAdapter(b);
bAdapter.a();
}
}
输出结果
我是B接口的适配器,我实现了A接口,正在执行实现A接口类的a方法
执行实现B接口类的b方法
我们调用了A接口中的a方法,确实现了B接口中的b方法,而对于A接口来说,它并未察觉到这是适配器起了作用