Skip to content
On this page

适配器模式

传统的 UML 类图

简易 UML 类图

代码

javascript
class Adaptee {
    specificRequest() {
        return '德国标准的插头'
    }
}

class Target {
    constructor() {
        this.adaptee = new Adaptee()
    }
    request() {
        let info = this.adaptee.specificRequest()
        return `${info} 转换器 -中国标准的插头`
    }
}

// 测试
let target = new Target()
target.request()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

场景

封装 / 旧接口

javascript
// 自己封装的 ajax ,使用方式如下:
ajax({
    url: '/getData'
    type: 'Post',
    dataType: 'json',
    data: {
        id:"123"
    }
})
.done(function(){})
// 但因为历史原因,代码中全都是:
// $.ajax({..})

var $ = {
    ajax:function(options) {
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

设计原则验证

  • 将旧接口和使用者进行分离
  • 符合开放封闭原则
沪ICP备20006251号-1