Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript设计模式(十四):适配器模式 #35

Open
yangrenmu opened this issue Sep 22, 2020 · 0 comments
Open

JavaScript设计模式(十四):适配器模式 #35

yangrenmu opened this issue Sep 22, 2020 · 0 comments
Labels

Comments

@yangrenmu
Copy link
Owner

介绍

适配器模式:适配器模式的作用是将两个软件实体间的接口不兼容的问题。使用适配器模式之后,原本由于接口不兼容而不能工作的两个软件实体可以一起工作。

这个像我们使用的各种转接头。

例子

const googleMap = {
  show: function () {
    console.log('开始渲染谷歌地图')
  }
}

const renderMap = function (map) {
  if (map.show instanceof Function) {
    map.show()
  }
}

renderMap(googleMap)

假如这个时候,百度地图的渲染接口是下面这样的:

const baiduMap = {
  display: function() {
    console.log('开始渲染百度地图')
  }
}

百度地图的渲染接口是display ,而不是show。这个时候,我们就可以编写一个适配器来解决问题。

const googleMap = {
  show: function () {
    console.log('开始渲染谷歌地图')
  }
}

const baiduMap = {
  display: function () {
    console.log('开始渲染百度地图')
  }
}

const baiduAdapter = {
  show: function () {
    return baiduMap.display()
  }
}

const renderMap = function (map) {
  if (map.show instanceof Function) {
    map.show()
  }
}

renderMap(googleMap)
renderMap(baiduAdapter)

小结

适配器模式主要是用来解决已有的对象接口之间的不匹配问题,它不需要改变现有的接口,就能使它们协同工作。

@yangrenmu yangrenmu added the mode label Sep 22, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant