美文网首页
设计模式(三)-适配器模式

设计模式(三)-适配器模式

作者: 仔崽06 | 来源:发表于2021-01-22 10:42 被阅读0次
    适配器模式

    适配器模式:将一个类(对象)的接口(方法或属性),转化为另一个接口以满足客户端的需求,不需要修改客户端的代码,使类(对象)之间接口的不兼容问题通过适配器得以解决.

    • 图例


      image.png
    • 代码实现

    class Prower{
        charge(){
            return '220V'
        }
    }
    
    class Adaptor{
        constructor(power){
            this.power=new Prower()
        }
        charge(){
           let v=this.power.charge()
           return `${v}=>12V`
        }
    }
    
    class Client{
        constructor(){
            this.adaptor=new Adaptor()
        }
        use(){
            console.log(this.adaptor.charge())
        }
    }
    
    let client=new Client()
    client.use() //220V=>12V
    
    
    • 应用场景
    //ajax请求参数
    function ajax(options){
        let defaultOptions={
            methods:'get',
            dataType:'json'
        }
        options=Object.assign(defaultOptions,options)
        console.log(options) //{ methods: 'post', dataType: 'json', url: 'www.baidu.com' }
    }
    
    ajax({
        url:'www.baidu.com',
        methods:'post'
    })
    
    //vue的计算属性
    <template>
          <div>
                <span>{{name}}</span>
                <span>{{upperName}}</span>
          </div>
    </template>
    <script>
         export default{
              data(){
                  return{
                        name:'zdb'
                  }
              },
              computed:{
                   upperName(){
                        return this.name.toUpperCase()
                   }
              }
         }
    </script>
    
    • 优点

    1.可以让两个没有关联的类一起运行.
    2.提高类的复用.
    3.增加类的透明度

    相关文章

      网友评论

          本文标题:设计模式(三)-适配器模式

          本文链接:https://www.haomeiwen.com/subject/dpkszktx.html