目录
- 类适配器
- 对象适配器
- 两种适配器的抉择
- 应用场景
类适配器
上面咱们应用Mac电脑和U盘适配的一个简略实例来理解类适配器的实现形式。
首先创立一个Mac的接口有读写的数据的性能
public interface MacInterface { void write(String msg); String read();}
而后有一个u盘的实例
public class UDisk { public void byWrite(String msg){ System.out.println(msg); } public String byRead(){ return "拜登家谱"; }}
然而mac接口间接连贯u盘所以咱们给它减少一个适配器,通过适配器连贯两者。
public class MacUsbAdaptor extends UDisk implements MacInterface{ @Override public void write(String msg) { super.byWrite(msg); } @Override public String read() { return super.byRead(); }}
public class AdaptorTest { @Test public void test(){ MacInterface macInterface = new MacUsbAdaptor(); System.out.println(macInterface.read()); macInterface.write("川普私密照片"); }}=====后果=====拜登家谱川普私密照片
对象适配器
应用和下面雷同的实例,通过组合的形式来实现对象适配器。
public interface MacInterface { void write(String msg); String read();}
public class UDisk { public void byWrite(String msg){ System.out.println(msg); } public String byRead(){ return "拜登家谱"; }}
public class MacUsbAdaptor implements MacInterface { private UDisk disk; public MacUsbAdaptor(UDisk disk) { this.disk = disk; } @Override public void write(String msg) { //适配过程中必定波及到一些 “适配” 的过程,比如说对立格局 disk.byWrite(msg); } @Override public String read() { return disk.byRead(); }}
public class AdaptorTest { @Test public void test(){ MacInterface macInterface = new MacUsbAdaptor(new UDisk()); System.out.println(macInterface.read()); macInterface.write("川普私密照片"); }}=====后果=====拜登家谱川普私密照片
两种适配器的抉择
- 被适配的类(如UDisk)的接口(类外面的办法)不多,两者都能够
- 被适配的类的接口较多而且接口大多数都须要和接口类(如 MacInterface)中的办法适配,那么能够抉择类适配器,这样能够复用被适配类中的办法,节俭代码量。
- 被适配的类的接口较多而且其接口和接口类(如 MacInterface)中的办法适配的不多,那么能够选择对象适配器,组合绝对于继承更加灵便。
应用场景
- 原有接口无奈批改但又必须疾速兼容新接口
- 不同数据格式、协定之间的转换
- 须要应用内部组件组合成新组件来提供性能,而又不想反复开发局部性能