桥接模式

18 阅读1分钟

桥接模式

目的

抽象出一些对象/方法的通用部分,再桥接对象的特别部分,旨在简化代码。

场景

操作一系列对象/方法时存在一系列相同的行为。

示例代码

// old
function f1(){
    axios.get("token").then((res)=>{
        console.log(res.data)
    })
}

function f2(){
    axios.get("token").then((res)=>{
        console.log(res.mes)
    })
}

function f3(){
    axios.get("token").then((res)=>{
        console.log(res.status)
    })
}

function fn(handler){
    axios.get("token").then((res)=>{
        handler(res)
    })
}

// 配合装饰者模式,提高易用性

function newF1(){
    fn((res)=>{console.log(res.data)})
}

function newF2(){
    fn((res)=>{console.log(res.mes)})
}

function newF3(){
    fn((res)=>{console.log(res.status)})
}