js设计模式之中介者模式

一、简单介绍

在日常开发中,我们将行为封装成一个个对象,在加强了复用性的同时,各个对象之间的联系也加强了,有时也会反过来降低复用性。

中介者模式就是添加一个中介者对象,接触对象和对象之间的耦合关系。它可以将联系紧密的对象解耦。命令模式重点在于命令的下达,更多的是单向的流动;发布订阅模式重点在于触发特定条件时的消息推送,或者说是事件执行。中介者的重点在于集中处理逻辑,不关心消息来源。

二、使用场景

在多个对象共享一些状态时,如果要达到状态的实时更新,各个对象就要保存其他对象的引用,这样就会造成对象之间的耦合。这时,我们可以用一个中介者对象专门处理状态的更新。

三、示例

假设每个部门有不同的月度预算,比如交通额度为500,餐补额度为300,。然后部门下面每个人对应的报销项加起来不能超过部门对应的报销项的限额。

class Person {
  constructor(name) {
    this.name = name;
    this.id = Math.random();
    this.money = {};
  }
  updateMoney(type, count, handle) {
    const flag = handle.addMoney(this.id, type, count);
    if (flag) {
      this.money[type] = count;
    }
  }
}
class MoneyHandle {
  constructor() {
    this.money = {};
    this.limit = {};
  }
  updateLimit(type, count) {
    this.limit[type] = count;
  }
  addMoney(id, type, count) {
    if (sum)
      if (!this.money) {
        this.money[type] = [
          {
            id,
            count
          }
        ];
      }
    const item = this.money[type].find(item => item.id === id);
    let sum;
    if (!item) {
      sum = this.getSunCount(type);
      if (sum + count > this.limit[type]) {
        console.log(`${type}类型报销项费用已超标,此次操作无效`);
        return false;
      }
      this.money[type].push({
        id,
        count
      });
    } else {
      sum = this.getSunCount(type);
      if (sum + count - item.count > this.limit[type]) {
        console.log(`${type}类型报销项费用已超标,此次操作无效`);
        return false;
      }
      item.count = count;
      return true;
    }
  }
  getSunCount(type) {
    if (!this.money[type]) return 0;
    this.money[type].reduce((sum, item) => {
      sum += item.count;
      return sum;
    }, 0);
  }
}
class Department {
  constructor() {
    this.person = [];
    this.money = {};
  }
  updateMoney(type, count) {
    this.money[type] = count;
  }
}

这这个例子中,我们用了一个MoneyHandle 对象来计算各项费用的合计,在更新时,计算最新的费用是否已超标,如果超标则提示,并且不会更新这个人的费用情况。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值