1. 定义
将一个类的接口,转换为客户期望的另一个接口,让原本接口不相容的类可以合作无间。
2. 角色
- Target:目标抽象类
- Accepter:适配器类
- Acceptee:适配者类
- Client:客户类
3. 特点
- 优点:通过引入一个适配器类来重用现有适配者类,而无需修改原代码,提高了适配者类代码的复用性。
- 缺点:若使用类适配器,对于Java等语言来说只支持单继承,因此只能有一个适配者类。
4.示例
Duck接口(Target):
public interface Duck {
void say();
}
假设已实现了许多不同类型的鸭子并且其鸭子叫say方法的实现不同,如今需新增一个鹅类,其叫法与鸭子类不同,用specificSay实现。
Goose(Adaptee):
public class Goose {
public void specificSay() {
System.out.println("gugugu");
}
}
若需要将鹅包装成一个鸭子,则需要使用适配器。
Adapter:
public class Adapter implements Duck {
private Goose goose;
public Adapter(Goose goose) {
this.goose = goose;
}
@Override
public void say() {
goose.specificSay();
}
}
测试类:
public class TestAdapter {
public static void main(String[] args) {
Duck duck = new Adapter(new Goose());
duck.say();
}
}
// 输出
// gugugu
参考:
1. 《Head First 设计模式》
2. 《图说设计模式》 https://design-patterns.readthedocs.io/zh_CN/latest/structural_patterns/adapter.html