定义:将一个类的接口转换成用户期望的另一个接口
使原本接口不兼容的类可以一起工作
结构型
应用场景:
已经存在的类,他的方法和需求不匹配时(方法结果相同或相似)
功能类似而接口不相同的情况下的解决方案
优点:
能提高类的透明性和复用,现有的类复用但不需要改变
目标类和适配器 类解耦,提高程序扩展性
符合开闭原则
类:
public class Adapteee { public void adapteeRequest(){ System.out.println("被适配着的方法"); } }
public interface Target {
void request();
}
public class ConcreteTarget implements Target {
public void request() {
System.out.println("目标方法");
}
}
public class Adapter extends Adapteee implements Target{
public void request() {
super.adapteeRequest();
}
}
public class Test {
public static void main(String[] args) {
Target target=new ConcreteTarget();
target.request();
Target adapterTarget=new Adapter();
adapterTarget.request();
}
}
对象:
public class Adapteee { public void adapteeRequest(){ System.out.println("被适配着的方法"); } } public class ConcreteTarget implements Target { public void request() { System.out.println("目标方法"); } } public class Adapter implements Target{ private Adapteee adapteee=new Adapteee(); public void request() { adapteee.adapteeRequest(); } }
public class Test {
public static void main(String[] args) {
Target target=new ConcreteTarget();
target.request();
Target adapterTarget=new Adapter();
adapterTarget.request();
}
}
实际应用:
public class AC220 { public int outputAC220v(){ int output=220; System.out.println("输出交流电"+output+"V"); return output; } } public interface DC5 { int outputDC5V(); } public class PowerAdapter implements DC5{ private AC220 ac220=new AC220(); public int outputDC5V() { int adapterInput=ac220.outputAC220v(); int adapterOutput=adapterInput/44; System.out.println("使用PowerAdapter输入AC:"+adapterInput+"V"+"输出DC:"+adapterOutput+"V"); return adapterOutput; } } public class Test { public static void main(String[] args) { DC5 dc5=new PowerAdapter(); dc5.outputDC5V(); } }