一、适配器的定义
适配器就是将原本不匹配的东西结合到一块,如:小米手机充电,使用安卓线+转换头(适配器),苹果4s充电,使用大插头+转换头(适配器)。通过这些例子,就能知道适配器就是将不能使用的事物通过某种方式的转换成功使用。
二、适配器的类图
三、适配器需要的元素
①客户端,适配器的使用者
②目标类(三项插头)
③适配器 (两项转三项插头)
④现有类 (两项插头)
四、适配器的实现
1.类适配器 (适配器继承现有类,实现目标类)
public interface PlugWithThree { //充电 void charge(); } |
public class PlugWithTwo{ public void charge() { System.out.println("两相插头充电!"); } } |
public class ThreeToTwoAdapter extends PlugWithTwo implements PlugWithThree { @Override public void charge() { super.charge(); System.out.print("转为三相插头充电"); } } |
public class Computer { public PlugWithThree plugWithThree; public Computer(PlugWithThree plugWithThree){ this.plugWithThree = plugWithThree; } public void charge(){ plugWithThree.charge(); } public static void main(String[] args) { Computer computer = new Computer(new ThreeToTwoAdapter()); computer.charge(); } } |
结果:
2.组合适配器 (客户端调用目标类(适配器)、适配器调用现有类)
public class ThreeToTwoAdapter implements PlugWithThree {
private PlugWithTwo plugWithTwo;
public ThreeToTwoAdapter(PlugWithTwo plugWithTwo){
this.plugWithTwo = plugWithTwo;
}
@Override
public void charge() {
plugWithTwo.charge();
System.out.print("转为三相插头充电");
}
} |
运行结果一致。
3.接口适配器
针对一个接口有很多方法,但是调用的时候,只调用其中的几个方法。如果直接实现接口会出现很多不必要的方法。所以,使用适配器类来实现那个接口(方法内容为空),然后使用实现类来继承适配器。
public interface Methods { void a(); void b(); void c(); void d(); void e(); } |
public class Adapter implements Methods{ @Override public void a() {} @Override public void b() {} @Override public void c() {} @Override public void d() {} @Override public void e() {} } |
public class Target extends Adapter{ @Override public void a() { super.a(); System.out.println("new a();"); } @Override public void b() { super.b(); System.out.println("new b();"); } } |
运行结果:
五、总结
1.前两种的使用方法差距不大,使用的场景也是差不多,解决那些不匹配的事物
2.第三种适配器,适用于方法调用,并且方法比较多的类上面