- 模式定义
将一个类的接口转换成客户希望的另一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作
- 应用场景
1.当你希望使用某些现有类,但其接口与您的其他代码不兼容时,请使用适配器类。
2.当你希望重用几个现有的子类,这些子类缺少一些不能添加到超类中的公共功能时,请使用该模式。
- 优点
1.符合单一职责原则
2.符合开闭原则
对象适配器模式
public class AdapterTest1 {
public static void main(String[] args) {
Adaptee adaptee = new Adaptee();
Target target = new Adapter(adaptee);
System.out.println(target.outPut5v());;
}
}
class Adaptee{
public int outPut220v(){
return 220;
}
}
interface Target{
int outPut5v();
}
//Object Adapter 对象适配器模式
class Adapter implements Target {
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public int outPut5v() {
return 5;
}
}
类适配器模式
public class AdapterTest2 {
public static void main(String[] args) {
Adapter adapter = new Adapter();
adapter.OutPut5v();
}
}
class Adaptee{
public int outPut220v(){
return 220;
}
}
interface Target{
int OutPut5v();
}
class Adapter extends Adaptee implements Target{
@Override
public int OutPut5v() {
int i = outPut220v();
System.out.println("电压由"+i+"转换为5v");
return 5;
}
}



