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:
  }
})

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

相关推荐
碎梦归途6 天前
23种设计模式-结构型模式之外观模式(Java版本)
java·开发语言·jvm·设计模式·intellij-idea·外观模式
小马爱打代码13 天前
设计模式:外观模式 - 简化复杂系统调用的利器
设计模式·外观模式
骊山道童13 天前
设计模式-外观模式
设计模式·外观模式
程序员沉梦听雨16 天前
外观模式详解
java·设计模式·外观模式
nlog3n23 天前
Java外观模式详解
java·开发语言·外观模式
Niuguangshuo23 天前
Python 设计模式:外观模式
python·设计模式·外观模式
NorthCastle1 个月前
设计模式-结构型模式-外观模式
java·设计模式·外观模式
系统工程实验室1 个月前
设计模式之外观模式
设计模式·外观模式
Antonio9151 个月前
【Q&A】外观模式在Qt中有哪些应用?
数据库·qt·外观模式
Hanson Huang1 个月前
23种设计模式-外观(Facade)设计模式
java·设计模式·外观模式·结构型设计模式