1.概念
充当两个不兼容接口之间的桥梁,把原本的接口转换成目标需要的接口
2.为什么需要使用适配器模式
- 开始设计时候,考虑的不周全,类设计的有缺陷
- 版本升级,某些接口需要删除,需要兼容老版本接口
- 替换依赖的外部系统
- 其它的情况 因为适配类使用范围比较广泛,所以使用的情况也就比较多,这边稍微罗列了几种情况
3.代码实现
适配器的实现一般分为两种,一种是类继承的方式实现,一种是通过包装对象来实现
3.1 范例
- 类设计不周全
class A {
f() {
console.log(1);
}
g() {
console.log(2);
}
h() {
console.log(3);
}
}
interface B {
m();
}
class adapter extends A implements B {
m() {
console.log(4);
}
}
let a: adapter = new adapter();
a.f();
a.g();
a.h();
a.m();
- 版本升级时某些接口需要删除,需要兼容老版本接口
//deprecated
class OldClass {
private _new: NewClass = new NewClass();
f() {
this._new.f();
}
g() {
this._new.g();
}
h() {
this._new.h();
}
}
class NewClass {
f() {
console.log(1);
}
g() {
console.log(2);
}
h() {
console.log(3);
}
m() {
console.log(4);
}
}
let adaptor = new OldClass();
adaptor.f();
adaptor.g();
adaptor.h();