JavaScript設計模式之適配器模式

介紹

  • 舊接口格式和使用者不兼容
  • 中間需要加一個適配轉(zhuǎn)換接口

實例

  • 電源適配器

UML

image
  • 簡化之后


    image
  • 在客戶與原類中,如果需求不滿足,那么實現(xiàn)一個Adapter繼承原類實現(xiàn)客戶需要的新功能

代碼演示

    class Adaptee{
        specificRequest(){
            return '外國標準的適配器'
        }
    }
    class Target{
        constructor(){
            this.adaptee = new Adaptee()
        }
        request(){
            let info = this.adaptee.specificRequest()
            return `${info}-轉(zhuǎn)換器-中國生產(chǎn)的`
        }
    }

    //測試
    let target = new Target()
    let res = target.request()

    console.log(res);
  • 最終將德國的轉(zhuǎn)換成中國產(chǎn)的

場景

  • 封裝舊接口
  • vue computed

封裝舊接口

    //自己封裝的ajax 使用如下
    ajax({
        url:'/user/getData',
        type:'post',
        dataType:'json',
        data:{
            id:'1123'
        }
    })
    .done(function () {

    })

    //但是項目之前是 $.ajax({...})
    //現(xiàn)在要替換成自己封裝的ajax 成本太高 故做一層適配
    var $ = {
        ajax:function (options) {
            return ajax(options)
        }
    }

vue computed

    <div id="app">
        <div>正序:{{msg}}}</div>
        <div>倒序:{{reverMsg}}</div>
    </div>
    const vm = new Vue({
        el:'#app',
        data:{
            msg:'w候人兮猗'
        },
        computed:{
            reverMsg:function () {
                return this.msg.split().reverse().join('')
            }
        }
    })

原文:https://www.ahwgs.cn/javascriptshejimoshizhishipeiqimoshi.html
代碼:https://github.com/ahwgs/design-pattern-learning/tree/master/5.JavaScript%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E4%B9%8B%E9%80%82%E9%85%8D%E5%99%A8%E6%A8%A1%E5%BC%8F

?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容