一、对象适配器模式介绍
基本思路和类的适配器模式相同,只是将Adapter类作修改,不是继承src类,而是持有src类的实例,以解决兼容性的问题。 即:持有 src类,实现 dst 类接口,完成src->dst的适配。 根据“合成复用原则”,在系统中尽量使用关联关系来替代继承关系。 对象适配器模式是适配器模式常用的一种。
二、使用对象适配器完成上一篇文章的问题
代码:
public class Voltage220V {
public int output220V ( ) {
int src = 220 ;
System. out. println ( "电压=" + src + "伏" ) ;
return src;
}
}
public interface IVoltage5V {
public int output5V ( ) ;
}
public class VoltageAdapter implements IVoltage5V {
private Voltage220V voltage220V;
public VoltageAdapter ( Voltage220V voltage220v) {
this . voltage220V = voltage220v;
}
@Override
public int output5V ( ) {
int dst = 0 ;
if ( null != voltage220V) {
int src = voltage220V. output220V ( ) ;
System. out. println ( "使用对象适配器,进行适配~~" ) ;
dst = src / 44 ;
System. out. println ( "适配完成,输出的电压为=" + dst) ;
}
return dst;
}
}
public class Phone {
public void charging ( IVoltage5V iVoltage5V) {
if ( iVoltage5V. output5V ( ) == 5 ) {
System. out. println ( "电压为5V, 可以充电~~" ) ;
} else if ( iVoltage5V. output5V ( ) > 5 ) {
System. out. println ( "电压大于5V, 不能充电~~" ) ;
}
}
}
测试类:
public class Client {
public static void main ( String[ ] args) {
System. out. println ( " === 类适配器模式 ====" ) ;
Phone phone = new Phone ( ) ;
phone. charging ( new VoltageAdapter ( new Voltage220V ( ) ) ) ;
}
}
结果图:
三、对象适配器模式注意事项和细节
对象适配器和类适配器其实算是同一种思想,只不过实现方式不同。根据合成复用原则,使用组合替代继承, 所以它解决了类适配器必须继承src的局限性问题,也不再要求dst必须是接口。 使用成本更低,更灵活。