# 六.适配器模式

  • 旧的接口和使用者不兼容
  • 中间加一个适配器转换接口

# 1.类图

# 2.代码

"use strict"
var Power = /** @class */ (function () {
  function Power() {}
  Power.prototype.charge = function () {
    return "220v"
  }
  return Power
})()
var Adapter = /** @class */ (function () {
  function Adapter() {
    this.power = new Power()
  }
  Adapter.prototype.charge = function () {
    var power = this.power.charge()
    return power + "=>120V"
  }
  return Adapter
})()
var Client = /** @class */ (function () {
  function Client() {
    this.adapter = new Adapter()
  }
  Client.prototype.use = function () {
    console.log(this.adapter.charge())
  }
  return Client
})()
new Client().use()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

# 3.场景

# 3.1 插件适配

  • 适配参数
  • 适配后端接口数据
function ajax(options) {
  let _deafult = {
    method: "GET",
    dataType: "json",
  }
  for (let attr in options) {
    _default[attr] = options[attr] || _default[attr]
  }
}
function get(url) {
  let options = { method: "GET", url }
  ajax(options)
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# 3.1 promisify

let fs = require("fs")
function promisify(readFile) {
  return function (filename, encoding) {
    return new Promise(function (resolve, reject) {
      readFile(filename, encodeing, function (err, data) {
        if (err) {
          reject(err)
        } else {
          resolve(data)
        }
      })
    })
  }
}
let readFile = promisify(fs.readFile)
readFile("./1.txt", "utf8").then((data) => console.log(data))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16