概念
将一个接口转换成客户需要的接口,让没有任何关系的类可以一起工作
适配器既可以作为类结构型模式,也可以作为对象结构型模式
对象适配器模式中,适配器和适配者之间是关联关系
类适配器模式中,适配器与适配者之间是继承(或实现)关系
角色
Target(目标抽象类):定义客户需要的接口,可以是抽象类、接口、具体类
Adapter(适配器类):调用另一个接口作为转换器进行二者间的适配
Adaptee(适配者类):被适配的角色,一般是个具体类,包含了客户需要的内容
类适配器
设计与实现:将220v电压转换为50v输出
1、提供目标
package com.xjion.adaptee;
//50v电力接口
public interface PowerTarget {
public int output50();
}
2、创建适配者
package com.xjion.adaptee;
public class PowerAdaptee {
private int output = 220;
public int output220V() {
System.out.println("输出电压"+output);
return output;
}
}
3、提供适配器(转换)
package com.xjion.adaptee;
public class PowerAdapter extends PowerAdaptee implements PowerTarget {
@Override
public int output50() {
int output = output220V();
System.out.println("电源适配器开始工作,电压:"+output);
output = 50;
System.out.println("电源适配器工作完成,电压:"+output);
return output;
}
}
4、测试
package com.xjion.adaptee;
public class AdapterTest {
public static void main(String[] args) {
PowerTarget target = new PowerAdapter();
target.output50();
}
}
对象适配器模式
与类适配器不同,Adapter只实现Target接口不继承Adaptee,而使用聚合方式引用Adaptee
实现
package com.xjion.adaptee;
public class PowerAdapter2 implements PowerTarget {
private PowerAdaptee powerAdaptee;
@Override
public int output50() {
int output = powerAdaptee.output220V();
System.out.println("电源适配器开始工作,电压:"+output);
output = 50;
System.out.println("电源适配器工作完成,电压:"+output);
return output;
}
public PowerAdapter2(PowerAdaptee powerAdaptee) {
super();
this.powerAdaptee = powerAdaptee;
}
}
package com.xjion.adaptee;
public class AdapterTest {
public static void main(String[] args) {
PowerTarget target = new PowerAdapter2(new PowerAdaptee());
target.output50();
}
}
实现了PowerTarget(目标角色),在创建对象时引入PowerAdaptee(适配者角色)
比较
类适配器:是适配者的子类,可以在适配器中置换适配者的方法(重写),灵活性强,只能有一个
对象适配器:非子类,可以把多个不同的适配者适配到一个目标,可以将适配者和他的子类都适配到目标接口