一、定義
通過提供抽象化和現(xiàn)實(shí)化之間的橋接結(jié)構(gòu)俺驶,實(shí)現(xiàn)二者的解耦。
2個(gè)角色:
(1)擴(kuò)充抽象類
(2)具體實(shí)現(xiàn)類
二、舉例
eg1: github上面原有的例子(https://github.com/sohamkamani/javascript-design-patterns-for-humans#-bridge)票从。
// 場(chǎng)景:更換主題
// About Careers是兩個(gè)抽象類,都有自己的主題成員
class About{
constructor(theme) {
this.theme = theme
}
getContent() {
return "About page in " + this.theme.getColor()
}
}
class Careers{
constructor(theme) {
this.theme = theme
}
getContent() {
return "Careers page in " + this.theme.getColor()
}
}
// DarkTheme LightTheme AquaTheme是具體實(shí)現(xiàn)類滨嘱,不同的主題有不同的效果
class DarkTheme{
getColor() {
return 'Dark Black'
}
}
class LightTheme{
getColor() {
return 'Off white'
}
}
class AquaTheme{
getColor() {
return 'Light blue'
}
}
// 調(diào)用
const darkTheme = new DarkTheme()
const about = new About(darkTheme)
const careers = new Careers(darkTheme)
console.log(about.getContent() )// "About page in Dark Black"
console.log(careers.getContent() )// "Careers page in Dark Black"
eg2:事件監(jiān)聽
/*
點(diǎn)擊事件獲取數(shù)據(jù)
弊端:該函數(shù)直接使用this.id,只能工作在瀏覽器中峰鄙,如果要對(duì)這個(gè)API函數(shù)做單元測(cè)試,或在命令行環(huán)境中執(zhí)行它太雨,是非常不方便的
*/
getData () {
api.fetchCompanyWalletApi({id: this.id}).then(data => {
// do sth
})
}
/*
1吟榴、將id作為參數(shù)傳遞
2、用橋接模式把抽象隔離開來
好處:拓寬了適用范圍囊扳,因?yàn)楝F(xiàn)在getData 并沒有和事件對(duì)象捆綁在一起吩翻,只需要提供一個(gè)ID就可以在單元測(cè)試中運(yùn)行這個(gè)API。此外锥咸,也可以在命令行環(huán)境中對(duì)這個(gè)接口進(jìn)行快速測(cè)試狭瞎。
*/
getData (id) {
api.fetchCompanyWalletApi({id: id}).then(data => {
// do sth
})
}
// 綁定事件
function getDataBridge(){
getData (this.id);
}
eg3:連接公開的API代碼和私用實(shí)現(xiàn)的代碼
let Student = function () {
// 私有變量
let name = 'aa';
// getName 訪問私用成員變量 name(特權(quán)函數(shù))
this.getName = function () {
return name;
}
// 私有方法
let getAge = function () {
// do sth
return 1;
}
// getAgeBridge 訪問私用方法 name(特權(quán)函數(shù))
this.getAgeBridge = function () {
return getAge ()
}
}
let student = new Student()
student.getName()
student.getAgeBridge()
eg3:橋接模式聯(lián)合幾個(gè)類
const Fn1 = function(a) {
// dosomething...
}
const Fn2 = function(b) {
// dosomething...
}
const Bridge = function(a, b){
this.one = new Fn1(a)
this.two = new Fn2(b)
}
三、總結(jié)
優(yōu)點(diǎn):
分離接口和實(shí)現(xiàn)部分
提供可擴(kuò)展性
實(shí)現(xiàn)細(xì)節(jié)對(duì)客戶透明搏予,可以對(duì)客戶隱藏實(shí)現(xiàn)細(xì)節(jié)
缺點(diǎn):
大量的類將導(dǎo)致開發(fā)成本增加脚作,同時(shí)在性能方面可能也會(huì)有所降低