JavaScript 设计模式之外观模式

外观模式

我们为啥要使用外观模式呢,其实我们在使用各种 js 库的时候常常会看到很多的外观者模式,也正是这些库的大量使用,所以使得兼容性更广泛,通过外观者模式来封装多个功能,简化底层操作方法

javascript 复制代码
const A = {
  g: function (id) {
    return document.querySelector(`#${id}`)
  },
  css: function (id, key, value) {
    this.g(id).style[key] = value
    return this
  },
  attr: function (id, key, value) {
    this.g(id)[key] = value
    return this
  },
  html: function (id, html) {
    this.g(id).innerHTML = html
    return this
  }
}


A.css('box','background','red') // 为 id 为 box 的 盒子设置 background 样式属性为 red

数据适配

在我们写方法时,通常会传递参数的形式来传递数据

javascript 复制代码
function fun(arg1,arg2,arg3,...){
    // todo:
}

但是我们更应该这样来写

javascript 复制代码
function fun(opts = {}) {
    const {a,b,c} = opts
    // opts.xx
    // todo:
}

使用一个对象来接受一些多个参数,使用时进行结构等方式读取数据,这样就避免了多个参数导致数据传递错误问题了,其实在很多的框架中也常常看到这种,比如 Vue 中

javascript 复制代码
import { createApp, ref } from 'vue'

createApp({
  setup() {
    return {
      count: ref(0)
    }
  }
}).mount('#app')

这 createApp 方法就单单只是传递一个对象来作为一个参数,而不是一二三个参数

比如 jQuery 中

javascript 复制代码
$.ajax({
  url: 'xx',
  method: 'get',
  dataType: 'json',
  success: function (data) {
    // todo:
  }
})

这种例子也是非常的多,这样的好处就是方便后期扩展,对于后期堆加参数更有利。

相关推荐
wWYy.3 天前
外观模式(Facade Pattern)
sdk·外观模式
我登哥MVP7 天前
走进 Gang of Four 设计模式:外观模式
java·设计模式·外观模式
ttod_qzstudio11 天前
【软考设计模式】外观模式:复杂子系统的“门面“封装与代码填空精讲
设计模式·外观模式
老码观察2 个月前
设计模式实战解读(十一):外观模式——给复杂系统套一层壳
python·设计模式·外观模式
咖啡八杯2 个月前
GoF设计模式——外观模式
java·设计模式·外观模式
likerhood2 个月前
设计模式 · 外观模式(Facade Pattern)
设计模式·外观模式
c++之路2 个月前
外观模式(Facade Pattern)
算法·外观模式
蜡笔小马2 个月前
09.C++设计模式-外观模式
c++·设计模式·外观模式
多加点辣也没关系2 个月前
设计模式-外观模式
设计模式·外观模式
雪度娃娃2 个月前
结构型设计模式——外观模式
c++·设计模式·外观模式