意图
将一个类的接口转换成客户希望的另一个接口。Adapter模式使得原本由于接口不兼容而不能在一起工作的那些类可以一起工作。
结构
类适配器使用多重继承对一个接口与另一个接口进行匹配,
对象适配器依赖于对象组合
其中
- Target定义Client使用的与特定领域相关的接口
- Client与符合Target接口的对象协同
- Adaptee定义一个已经存在的接口,这个接口需要适配
- Adapter对Adaptee的接口与Target接口 进行适配
适用性
Adapter模式适用于:
- 想使用一个已经存在的类,而它的接口不符合要求。
- 想创建一个可以服用的类,该类可以与其他不相关的类或不可预见的类(即那些接口可能不一定兼容的类)协同工作。
- (仅适用于对象Adapter)想使用一个已经存在的子类,但是不可能对每一个都进行子类化一匹配它们的接口。对象适配器可以适配它的父类接口。
代码示例
假设我们有一个 LegacySystem
类,它使用一个旧接口 OldInterface
。我们希望将 LegacySystem
与一个新的系统集成,该系统使用一个新接口 NewInterface
。
// 旧接口
interface OldInterface {
void oldMethod();
}
// 新接口
interface NewInterface {
void newMethod();
}
// 适配器类
class Adapter implements NewInterface {
private OldInterface oldInterface;
public Adapter(OldInterface oldInterface) {
this.oldInterface = oldInterface;
}
// 适配器将新接口的方法映射到旧接口的方法
@Override
public void newMethod() {
oldInterface.oldMethod();
}
}
// 旧系统类
class LegacySystem implements OldInterface {
@Override
public void oldMethod() {
System.out.println("旧系统方法被调用");
}
}
// 客户端代码
public class Client {
public static void main(String[] args) {
// 创建旧系统对象
OldInterface oldSystem = new LegacySystem();
// 创建适配器,将旧系统包装成新接口
NewInterface newSystem = new Adapter(oldSystem);
// 使用新接口调用方法
newSystem.newMethod();
}
}
设计注释:
OldInterface
和NewInterface
定义了两个不兼容的接口。Adapter
类实现了NewInterface
,并包含一个OldInterface
对象的引用。Adapter
类的方法将NewInterface
的方法映射到OldInterface
的方法。Client
代码使用NewInterface
调用方法,而无需了解LegacySystem
的具体实现。