JavaScript 设计模式之代理模式

代理模式

其实这种模式在现在很多地方也都有使用到,如 Vue3 中的数据相应原理就是使用的 es6 中的 Proxy 代理及 Reflect 反射的方式来处理数据响应式

我们日常在使用数据请求时,也会用到一些代理的方式,比如在请求不同的域名,端口等会出现跨域的情况,这时就需要用到代理去获取对应的数据了,日常可能会用到 nginx 代理来获取,或者是 jsonp 的方式来获取

javascript 复制代码
const Car = function (name) { 
  this.name = name
}
const Mini = function (car) {
  this.car = car
  this.getPrice = function (price) {
    console.log(`当前的价格是${price}`)
  }
}
const Proxy = function (car) {
  this.car = car
  this.getPrice = function (price) {
    (new Mini(car)).getPrice(price)
  }
}

const car = new Proxy('BMW')
car.getPrice('23W') // 当前的价格是23W

这样就通过代理模式拿到了对应的数据

装饰器模式

通常我们在团队中使用一些公用方法时会遇到这种情况,在不改变他人代码的情况下如何通用他人的代码呢,这就需要使用到我们常用到的装饰器模式了,他便能很好的解决这种问题

javascript 复制代码
const Fun = function (name) {
  this.name = name
  this.sayHi = () => {
    console.log(`my name: ${this.name}`)
  }
  this.eat = (ttt) => {
    console.log(`${this.name} is eating`)
  }
}

const decor = function (decFn, fn) {
  decFn()
  return fn
}
const test = decor(function () {
  // todo: 需要做其他的事,自己的逻辑
  console.log('开始吃饭了~~')
}, new Fun('朴者和尚').eat)

test() // 朴者和尚 is eating

这种模式还是很好理解的,上面我们使用箭头函数,为了避免 this 指向问题,其实在团队协作中使用还是挺多的

javascript 复制代码
const Car = function (name) {
  this.name = name;
  this.cost = function (price=100) { 
    return price
  }
}
const BaoMaCar = function (car) {
  this.cost = function () {
    return car.cost() + 100
  }
}
const BenChiCar = function (car) {
  this.cost = function () {
    return car.cost() + 75
  }
}

const bao = new BaoMaCar(new Car('BMW'))
const ben = new BenChiCar(new Car('Audi'))
console.log(bao.cost()) // 200
console.log(ben.cost()) // 175

在不同的车类型价格上增加不同的定制

相关推荐
y***54888 小时前
Java设计模式之观察者模式
观察者模式·设计模式
明洞日记8 小时前
【设计模式手册010】组合模式 - 树形结构的优雅处理
java·设计模式·组合模式
帅中的小灰灰8 小时前
C++编程策略设计模式
开发语言·c++·设计模式
xuchaoxin13759 小时前
浏览器代理插件@按规则自动切换代理模式@ZeroOmega配置协议分流@http链接直连
代理模式·浏览器
鲸沉梦落11 小时前
23种常见设计模式
设计模式
Malone-AI12 小时前
设计模式之单例模式
单例模式·设计模式
Moe48813 小时前
Spring Boot 自动配置核心:AutoConfigurationImportSelector 深度解析
java·后端·设计模式
G***T69113 小时前
Java设计模式之责任链
设计模式
6***x54514 小时前
Java设计模式之策略模式
java·设计模式·策略模式
miss_you121314 小时前
策略模式 + 模板方法 + 注册式工厂 统一设计方案(营销优惠场景示例)
设计模式·工厂方法模式·策略模式·模板方法模式