js 适配器模式

来源:互联网 发布:电脑怎么修改淘宝评价 编辑:程序博客网 时间:2024/05/17 18:14

将一个类(对象)的接口(方法或者属性)转化成另外一个接口,以满足用户的需求,使类(对象)之间的接口不兼容问题通过适配器得以解决.

class Basketball {  playBasketball () {    console.log('投篮')  }  basketballTeam () {    console.log('五个人')  }}class Football {  playFootball () {    console.log('射门')  }  footballTeam () {    console.log('十一个人')  }}class Ball {  constructor (type) {    this.type = type    if (type === 'football') {      this.action = new Football()    } else if (type === 'basketball') {      this.action = new Basketball()    }  }  play () {    if (this.type === 'football') {      this.action.playFootball()    } else if (this.type === 'basketball') {      this.action.playBasketball()    }  }  team () {    if (this.type === 'football') {      this.action.footballTeam()    } else if (this.type === 'basketball') {      this.action.basketballTeam()    }  }}let ball = new Ball('football')ball.play()ball.team()let ball2 = new Ball('basketball')ball2.play()ball2.team()