概念
类似粘合剂,将两个不兼容的类融合在一起,在两者之间创建了一个混血儿,达到不修改原有代码情况下满足业务需求。
实现方式
- Target —— 目标角色接口,即我们所期待的接口
- Adaptee ——需要适配的接口(因为它现有接口无法满足业务需求)
- Adapter —— 适配器
1 类适配器模式
public interface Target {
public int get5V();
}
public class Adaptee {
public int get220V(){
return 220;
}
s}
public class Adapter extends Adaptee implements Target {
@Override
public int get5V(){
return 5;
}
}
public class Test {
public static void main(String[] args){
Adapter a = new Adapter();
a.get5V();
}
}
2 对象适配器模式(开发时尽量使用) 与类适配器不同的是,它并非用继承的关系连接Adaptee,而是通过代理(组合形式)。
public class Adapter implements Target {
Adaptee adaptee;
public Adapter(Adaptee a){
adaptee = a;
}
public int get220V(){
return a.get220V();
}
@Override
public int get5V(){
return 5;
}
}