适配器模式是指将一个类的接口转换成用户期望的另一个接口,使得原本不兼容的类可以一起工作。比如:手机充电需要5V的电压,而生活供电是220V电压,所以给手机充电就需要一个5V的充电器,这个充电器就是适配器。由此可见,适配器模式的出现是为了解决现有的类或接口不能满足需求,且无法直接修改的问题。
适配器模式包含的角色如下:
- 被适配者(Adaptee):比如:220V的电压就是被适配者,表示已经存在的类或对象;
- 目标角色(Target):比如:5V电压就是目标角色,也就是我们的期望接口、抽象类或具体类;
- 适配器(Adapter):比如:充电器就是适配器,它可以调用Adaptee和Target进行适配;
总之一句话,适配器模式是指Adapter可以根据Target接口中的方法来调用Adaptee中的方法。
其实现方案有两种:类适配器和对象适配器。
类适配器
public class Adaptee {
public int output220V() {
int output = 220;
System.out.println("输出" + output + "V电压");
return output;
}
}
public interface Target {
int output5V();
}
public class Adapter extends Adaptee implements Target {
@Override
public int output5V() {
int output = super.output220V() / 44;
System.out.println("输出" + output + "V电压");
return output;
}
}
public class Test {
public static void main(String[] args) {
Target target = new Adapter();
target.output5V();
}
}
输出220V电压
输出5V电压
对象适配器
public class Adapter implements Target {
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public int output5V() {
int output = adaptee.output220V() / 44;
System.out.println("输出" + output + "V电压");
return output;
}
}
public class Test {
public static void main(String[] args) {
Target target = new Adapter(new Adaptee());
target.output5V();
}
}
总结
- 系统需要使用一些现有的类,这些类的接口(方法名等)无法改变且不符合需要,则可以用适配器模式;
- 类适配器一次最多只能适配一个Adaptee,因为Java不支持多继承。