类适配器模式
类适配器模式介绍
基本介绍:Adapter类,通过继承src类,实现dst类接口,完成src->dst的适配。
package com.young.adapter.classadapter;
/**
* 被适配的类
*
* @author Shaw_Young
* @date 2020/10/7 14:12
*/
public class Voltage220V {
/**
* 输出220V电压
*/
public int output220V() {
int src = 220;
System.out.println("电压=" + src + "伏");
return src;
}
}
package com.young.adapter.classadapter;
/**
* 适配接口
*
* @author Shaw_Young
* @date 2020/10/7 14:14
*/
public interface IVoltage5V {
/**
* 输出5V电压
*
* @return 输出5V电压
*/
int output5V();
}
package com.young.adapter.classadapter;
/**
* 适配器类
*
* @author Shaw_Young
* @date 2020/10/7 14:15
*/
public class VoltageAdapter extends Voltage220V implements IVoltage5V {
@Override
public int output5V() {
//获取到220V电压
int srcV = output220V();
//转成5V
int dstV = srcV / 44;
return dstV;
}
}
package com.young.adapter.classadapter;
/**
* @author Shaw_Young
* @date 2020/10/7 14:18
*/
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,无法充电~~");
}
}
}
package com.young.adapter.classadapter;
/**
* @author Shaw_Young
* @date 2020/10/7 14:20
*/
public class Client {
public static void main(String[] args) {
System.out.println("===类适配器模式===");
Phone phone = new Phone();
phone.charging(new VoltageAdapter());
}
}
类适配器模式注意事项和细节
- Java是单继承机制,所以类适配器需要继承src类这一点算是一个缺点,因为这要求dst必须是接口,有一定局限性;
- src类的方法在Adapter中都会暴露出来,也增加了使用的成本;
- 由于其继承了src类,所以它可以根据需求重写src类的方法,使得Adapter的灵活性增强了。
网友评论