适配器模式
三种模式:类适配器、接口适配器、对象适配器
1、类适配器
定义
1、java是单继承机制,所以类适配器需要继承src类这一点算是一个缺点,因为这要求dst必须是接口,有一定局限性。
2、src类的方法在Adapter中会暴露出来,也增加了使用成本。
3、由于其继承了src类,所以他可以更具需求重写src类的方法,使得Adapter的灵活性增强了。
@Slf4j
public class Voltage220V {public int output220(){int src=220;log.info("输出{}伏电压",src);return src;}
}
public interface Voltage5V {public int output5V();
}
public class VoltageAdapter extends Voltage220V implements Voltage5V {@Overridepublic int output5V() {//获取220v电压int srcV = output220();//转为5v(降压处理)return srcV/44;}
}
@Slf4j
public class Phone {//充电方法public void charging(Voltage5V voltage5V) {if (voltage5V.output5V() == 5) {log.info("可以充电");} else if (voltage5V.output5V() > 5) {log.info("电压大于5V,无法充电");}}
}
@Slf4j
public class Client {public static void main(String[] args) {log.info("\n类适配器模式==============");Phone phone=new Phone();phone.charging(new VoltageAdapter());}
}
2、对象适配器
1、对象适配器和类适配器其实算是一种思想,只不过实现方式不同。根据合成复用原则, 使用组合替代继承,所以他解决了类适配器必须继承src的局限性问题,也不再要求dst必须是接口。
2、使用成本更低,更灵活
@Slf4j
public class Voltage220V {public int output220(){int src=220;log.info("输出{}伏电压",src);return src;}
}
public interface Voltage5V {public int output5V();
}
@Slf4j
public class VoltageAdapter implements Voltage5V {private Voltage220V voltage220V;public VoltageAdapter(Voltage220V voltage220V) {this.voltage220V = voltage220V;}@Overridepublic int output5V() {int dst = 0;if (null != voltage220V) {//获取220v电压int srcV = voltage220V.output220();log.info("适用对象适配器,进行适配...");//转为5v(降压处理)dst = srcV / 44;log.info("适配完成,输出电压为:{}伏", dst);}return dst;}
}
@Slf4j
public class Phone {//充电方法public void charging(Voltage5V voltage5V) {if (voltage5V.output5V() == 5) {log.info("可以充电");} else if (voltage5V.output5V() > 5) {log.info("电压大于5V,无法充电");}}
}
@Slf4j
public class Client {public static void main(String[] args) {log.info("\n对象适配器模式==============");Phone phone=new Phone();phone.charging(new VoltageAdapter(new Voltage220V()));}
}
3、接口适配器
1、一些书籍称为:适配器模式(Default Adapter Pattern)或缺省适配器模式(因为很多方法空实现)
2、当不需要全部实现接口提供的方法时,可先设计一个抽象类实现接口,并为该接口中的每一个方法提供默认实现(空方法),那么抽象类的子类可有选择地覆盖弗雷德某些方法实现需求。
3、适用于一个接口不想使用其所有的方法的情况。
public interface InterfaceAdapter {public void method1();public void method2();public void method3();public void method4();
}
//在AbstractAdapter我们将InterfaceAdapter的方法进行默认实现
public class AbstractAdapter implements InterfaceAdapter {//默认实现@Overridepublic void method1() {}@Overridepublic void method2() {}@Overridepublic void method3() {}@Overridepublic void method4() {}
}
@Slf4j
public class Client {public static void main(String[] args) {AbstractAdapter adapter= new AbstractAdapter(){@Overridepublic void method1() {log.info("使用了method1方法");}};adapter.method1();}
}
SpringMVC的HandlerAdapter使用了适配器模式
适配器模式的注意事项和细节
1、三种命名方式,都是根据src是以怎样的形式给Adapter(在Adapter里的形式)来命名的。
2、类适配器:以类给到,在Adapter里,就是将src当做类,继承。
对象适配器:以对象给到,在Adapter里,将src作为一个对象,持有。
接口适配器:以接口给到,在Adapter里,将src作为接口,实现。
3、Adapter模式最大的作用还是将原本不兼容的接口融合在一起工作。
4、实际开发中,实际用起来不拘泥于我们讲的三种经典形式。