//定义转换接口publicinterfacePowerConverter{intconvert(int power);}//定义适配器实现类publicclassPowerAdapterimplementsPowerConverter{privateint inputVoltage;privateint outputVoltage;publicPowerAdapter(int inputVoltage,int outputVoltage){this.inputVoltage = inputVoltage;this.outputVoltage = outputVoltage;}@Overridepublicintconvert(int power){return power / inputVoltage * outputVoltage;}}//定义需要适配器的设备类publicclassDevice{privatePowerConverter powerConverter;publicDevice(PowerConverter powerConverter){this.powerConverter = powerConverter;}publicvoidsetPowerConverter(PowerConverter powerConverter){this.powerConverter = powerConverter;}publicvoidturnOn(){int power =1000;// example power requirement for the device int convertedPower = powerConverter.convert(power);// use the converted power to operate the device }}//创建一个Device实例,并将一个PowerAdapter实例传递给它的构造函数。这样,适配器就可以在Device实例需要电源转换时进行转换publicclassMain{publicstaticvoidmain(String[] args){PowerAdapter adapter =newPowerAdapter(110,220);// converts 110V to 220V Device device =newDevice(adapter);// uses the adapter as a PowerConverter
device.turnOn();// uses the converted power to operate the device }}