创建型模式(5个)
结构型模式(7个)
适配器模式 Adapter
通过一个“适配器类”,让原本接口不兼容的两个类可以协同工作。
适配器模式的三个角色
-
目标类(Target)要使用的接口
-
被适配类(Adaptee)已经存在的类,但是它的接口和目标类不一致
-
适配器类(Adapter)将Target接口的请求转换为对Adaptee的调用
两种适配器实现方式
类型 | 实现方式 | 特点 |
---|---|---|
类适配器 | 使用继承,适配器继承 Adaptee 并实现 Target | 不推荐,因为 Java 不支持多继承 |
对象适配器 | 使用组合,在适配器中持有 Adaptee 对象 | 推荐,灵活 |
对象适配器案例
package adapter;
/**
* <p>
* 描述: 目标类
* 用来定义所需的抽象类或接口
* </p>
*
* @Author huhongyuan
*/
public interface USB {
void chargeWithUSB();
}
package adapter;
/**
* <p>
* 描述: 被适配类
* </p>
*
* @Author huhongyuan
*/
public class TypeC {
void chargeWithTypeC() {
System.out.println("使用TypeC充电");
}
}
package adapter;
/**
* <p>
* 描述: 适配器类
* </p>
*
* @Author huhongyuan
*/
public class TypeC2USBAdapter implements USB{
private TypeC typeC;
public TypeC2USBAdapter(TypeC typeC) {
this.typeC = typeC;
}
@Override
public void chargeWithUSB() {
typeC.chargeWithTypeC();
}
}
package adapter;
/**
* <p>
* 描述: 适配器测试
* </p>
*
* @Author huhongyuan
*/
public class AdapterTest {
public static void main(String[] args) {
TypeC2USBAdapter adapter = new TypeC2USBAdapter(new TypeC());
adapter.chargeWithUSB();
}
}