【设计模式】适配器模式
// 1. 旧款圆口充电器(被适配者)
class RoundHoleCharger {
public int getRoundHoleVoltage() {
return 5; // 输出5V电压
}
}
// 2. Type-C充电接口(目标接口)
interface TypeCCharger {
int getTypeCVoltage();
}
// 3. 适配器:将圆口充电器转为Type-C接口
class ChargerAdapter implements TypeCCharger {
private RoundHoleCharger roundHoleCharger;
public ChargerAdapter(RoundHoleCharger roundHoleCharger) {
this.roundHoleCharger = roundHoleCharger;
}
@Override
public int getTypeCVoltage() {
int voltage = roundHoleCharger.getRoundHoleVoltage();
System.out.println("适配器将圆口电压转换为Type-C电压");
return voltage; // 直接传递电压,可能包含转换逻辑
}
}
// 4. 使用示例
public class AdapterDemo {
public static void main(String[] args) {
RoundHoleCharger oldCharger = new RoundHoleCharger();
TypeCCharger typeCCharger = new ChargerAdapter(oldCharger);
System.out.println("Type-C电压:" + typeCCharger.getTypeCVoltage() + "V");
}
}