适配器模式介绍
适配器模式让某个类的接口转化为客户期望的类接口表示,实现兼容。别名称为包装器(Wrapper)
1 :类适配器
![](https://img.haomeiwen.com/i12775885/1d029f63b7ea682c.png)
//被适配的类
public class Voltage220V {
//输出220V的电压
public int output220V() {
int src = 220;
System.out.println("电压=" + src + "伏");
return src;
}
}
//适配接口
public interface IVoltage5V {
public int output5V();
}
//适配器类
public class VoltageAdapter extends Voltage220V implements IVoltage5V {
@Override
public int output5V() {
//获取到220V电压
int srcV = output220V();
int dstV = srcV / 44 ; //转成 5v
return dstV;
}
}
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, 不能充电~~");
}
}
}
public class Client {
public static void main(String[] args) {
System.out.println(" === 类适配器模式 ====");
Phone phone = new Phone();
phone.charging(new VoltageAdapter());
}
}
上面的VoltageAdapter 继承了目标类Voltage220V ,也就是VoltageAdapter本身就是一个目标类,但是由于Java单继承,这是一个局限性。
2 对象适配器
对象适配器与类适配器类似,只不过将继承关系改为了组合关系,用关联关系替代了继承关系。这样可以避免上面的继承问题。
![](https://img.haomeiwen.com/i12775885/0624174ad583d46e.png)
//适配器类
public class VoltageAdapter implements IVoltage5V {
private Voltage220V voltage220V; // 关联关系-聚合
//通过构造器,传入一个 Voltage220V 实例
public VoltageAdapter(Voltage220V voltage220v) {
this.voltage220V = voltage220v;
}
@Override
public int output5V() {
int dst = 0;
if(null != voltage220V) {
int src = voltage220V.output220V();//获取220V 电压
System.out.println("使用对象适配器,进行适配~~");
dst = src / 44;
System.out.println("适配完成,输出的电压为=" + dst);
}
return dst;
}
}
public class Client {
public static void main(String[] args) {
System.out.println(" === 对象适配器模式 ====");
Phone phone = new Phone();
phone.charging(new VoltageAdapter(new Voltage220V()));
}
}
3 接口适配器,有些书里面称:当不需要实现全部接口提供的方法时,可先设计一个抽象类实现接口,并且为每个接口方法都提供默认实现方法(空方法),那么该抽象类的子类可以有选择性的覆盖父类的某些方法来实现需求。
这种情况适合于不想使用所有方法的情况
![](https://img.haomeiwen.com/i12775885/b4c3072eec46a5e4.png)
public interface Interface4 {
public void m1();
public void m2();
public void m3();
public void m4();
}
//在AbsAdapter 我们将 Interface4 的方法进行默认实现
public abstract class AbsAdapter implements Interface4 {
//默认实现
public void m1() {
}
public void m2() {
}
public void m3() {
}
public void m4() {
}
}
public class Client {
public static void main(String[] args) {
AbsAdapter absAdapter = new AbsAdapter() {
//只需要去覆盖我们 需要使用 接口方法
@Override
public void m1() {
System.out.println("使用了m1的方法");
}
};
absAdapter.m1();
}
}
网友评论