适配器模式(Adapter pattern)
适配器模式将某个类的接口转换成客户端期望的另一个接口表示,目的是消除由于接口不匹配所造成的类的兼容性问题。
电源基类
public abstract class Power {
private float power;
private String unit="V";
public Power(float power){
this.power=power;
}
public float getPower() {
return power;
}
public void setPower(float power) {
this.power = power;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
}
220V电源接口
public interface IPower220 {
public void output220();
}
220V电源
public class Power220 extends Power implements IPower220{
public Power220(float power) {
super(power);
}
@Override
public void output220() {
System.out.println(this.getPower()+this.getUnit()+"电源");
}
}
12V电源接口
public interface IPower12 {
public void output12();
}
12V电源
public class Power12 extends Power implements IPower12{
public Power12(float power) {
super(power);
}
@Override
public void output12() {
System.out.println(this.getPower()+this.getUnit()+"电源");
}
}
对象适配器
对象适配器使用组合方法。
public class Adapter implements IPower12{
//待转换电源
private Power power;
public Adapter(Power power){
this.power=power;
}
/**
* description
*/
@Override
public void output12() {
//转换为12v的过程
System.out.println("12V电源");
}
}
测试类:
public class Demo {
public static void main(String[] args) {
Power220 power220=new Power220(220);
Adapter adapter =new Adapter(power220);
adapter.output12();
}
}
类适配器
类适配器使用继承方法。
public class Adapter extends Power implements IPower12{
public Adapter(float power) {
super(power);
}
@Override
public void output12() {
System.out.println("12V电源");
}
}
测试类:
public class Demo {
public static void main(String[] args) {
Adapter adapter =new Adapter(220);
adapter.output12();
}
}
适配器模式主要用于系统的升级扩展,或者版本兼容性上。