外观模式

19 阅读1分钟

外观模式

目的

简化使用者对于功能的调用。

场景

开发某个复杂功能时,我们可以把功能拆分成小模块,并按照一定的逻辑或者执行顺序重新组装以实现该复杂功能。该模式,可以有效的解耦调用者和子模块,使组件易用,降低学习成本。

// 简易外观模式
function fn1(){
    // do somthing here
}

function fn2(){
    // do somthing here
}

function fn3(){
    // do somthing here
}

fn1(),fn2(),fn3()

// 外观模式

function run(){
    fn1(),fn2(),fn3()
}

run()

场景实例

装饰模式在响应拦截器中的应用

function refreshToken(){
    // refresh token here
}

function apiReCall(calls){
    // recall here
}

function collectCalls(){
    // when token expired collect api calls to recall after token refreshed
    return collectedCalls
}

function jumpTo(url){
    // refresh token here
}

function apiCall(){
    return response
}

// 响应拦截器 - 刷新token
function tokenRefreshInterceptor(response){
    if(response.expired){
        let collectedCalls = collectCalls()
        await refreshToken()
        return apiReCall(collectedCalls)
    }
}

function apiCallWithTokenRefreshInterceptor(){
    tokenRefreshInterceptor(response)
    return response
}

apiCallWithTokenRefreshInterceptor()

// 响应拦截器 - 页面重定向
function redirectInterceptor(response){
    if(response.needRedirect){
        return jumpTo(response.redirectUrl)
    }
}

function apiCallWithRedirectInterceptor(){
    redirectInterceptor(response)
    return response
}

apiCallWithRedirectInterceptor()