JAVA适配器模式-案例

Java适配器模式

//定义转换接口
public interface PowerConverter {  
    int convert(int power);  
}
//定义适配器实现类
public class PowerAdapter implements PowerConverter {  
    private int inputVoltage;  
    private int outputVoltage;  
      
    public PowerAdapter(int inputVoltage, int outputVoltage) {  
        this.inputVoltage = inputVoltage;  
        this.outputVoltage = outputVoltage;  
    }  
      
    @Override  
    public int convert(int power) {  
        return power / inputVoltage * outputVoltage;  
    }  
}
//定义需要适配器的设备类
public class Device {  
    private PowerConverter powerConverter;  
      
    public Device(PowerConverter powerConverter) {  
        this.powerConverter = powerConverter;  
    }  
      
    public void setPowerConverter(PowerConverter powerConverter) {  
        this.powerConverter = powerConverter;  
    }  
      
    public void turnOn() {  
        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实例需要电源转换时进行转换
public class Main {  
    public static void main(String[] args) {  
        PowerAdapter adapter = new PowerAdapter(110, 220); // converts 110V to 220V  
        Device device = new Device(adapter); // uses the adapter as a PowerConverter  
        device.turnOn(); // uses the converted power to operate the device  
    }  
}

你可能感兴趣的:(JavaSE笔记,设计模式,java,适配器模式,开发语言,设计模式)