适配器模式 适配器模式(Adapter)的定义如下:将一个类的接口转换成客户希望的另外一个接口,使得原本由于接口不兼容而不能一起工作的那些类能一起工作。
适配器模式的结构 适配器模式通常涉及以下几个角色:
目标(Target): 定义客户端所期望的接口。
适配者(Adaptee): 定义一个已经存在的接口,需要适配这个接口以便与目标接口兼容。
适配器(Adapter): 适配器类通过继承或组合的方式持有适配者的引用,并将适配者的接口转换为目标接口。
适配器模式的类型 适配器模式有两种主要类型:
类适配器模式: 适配器类通过继承适配者类和目标接口来实现。 期望实现接口, 我们 用 mobilePhone 来表示期望实现的接口信息
1 2 3 4 5 6 7 package AdapterModel; public interface Target { public String mobilePhone(String model); }
原有接口 实体信息, 现在这个 不适用于最新的信息, 最初这个接口只支持信息是 xiaomi2
1 2 3 4 5 6 7 8 9 package AdapterModel;public class mobileAdaptee { public String model () { return "xiaomi2" ; } }
我们通过 实现我们期望的接口 并 继承原有的 接口信息 并 重新 处理,现在支持新款 xiaomi6
1 2 3 4 5 6 7 8 9 10 11 12 13 package AdapterModel;public class modelAdapter extends mobileAdaptee implements Target { @Override public String mobilePhone (String num) { String model = model(); if ("xiaomi" .equals(num)){ return model; } return "xiaomi6" ; } }
信息 展现
1 2 3 4 5 6 7 8 9 10 11 12 package AdapterModel;public class Main { public static void main (String[] args) { Target target = new modelAdapter (); String s = target.mobilePhone("xiaomi" ); System.out.println(s); String s1 = target.mobilePhone(null ); System.out.println(s1); } }
适配器类 Adapter 继承了 Adaptee 类,并实现了 Target 接口。 适配器类可以直接访问适配者类的所有方法。
对象适配器模式: 适配器类通过组合适配者对象来实现。 还是上面那个类, 现在在适配器里通过实现对象时同步创建
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 package AdapterModel; public class mobile1Adapter implements Target{ private mobileAdaptee mobileAdaptee; public mobile1Adapter(mobileAdaptee mobileAdaptee){ this.mobileAdaptee = mobileAdaptee; } @Override public String mobilePhone(String model) { if("xiaomi".equals(model)){ return mobileAdaptee.model(); } return "xiaomi6"; } }
通过适配器组合实例对象,在实现对他的接口更新适配 实现跟上面效果一样
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 package AdapterModel; public class Main { public static void main(String[] args) { // Target target = new modelAdapter(); // String s = target.mobilePhone("xiaomi"); // System.out.println(s); // String s1 = target.mobilePhone(null); // System.out.println(s1); Target target =new mobile1Adapter(new mobileAdaptee()); String s = target.mobilePhone("xiaomi"); System.out.println(s); String s1 = target.mobilePhone(null); System.out.println(s1); } }
适配器类 Adapter 实现了 Target 接口,并持有 Adaptee 类的一个实例。 适配器类通过组合适配者对象来实现适配。
适配器模式可以让你轻松地在现有系统中集成新组件,而无需修改现有代码。这有助于提高系统的灵活性和可维护性。