JavaScript设计模式-002

61 阅读1分钟

单例模式

保证一个类只有一个实例,提供访问它的全局访问点。

主要解决一个全局使用的类频繁创建销毁,占用内存。

es6之前写法

let Single = (function(){
  let instance
  function User(name, age) {
    this.name = name
    this.age = age
  }

  return function(name, age) {
    if(!instance) {
      //创建实例
      instance = new User(name, age)
    }
    return instance
  }
})()

if (Single() === Single()) {
  console.log(true);
}

es6之后写法

class Singleton {
  constructor(name, age) {
    if (!Singleton.instance) {
      this.name = name
      this.age = age
      Singleton.instance = this
    }
    return Singleton.instance
  }

}

console.log(new Singleton('zs', 66) === new Singleton('ls', 22));

类只有一份,首次创建一定没有instance,取反为真,创建instance。二次创建,取反为假,直接返回instance,达到单例目标。

装饰器模式

对已有功能进行扩展,不修改原有代码,并对其他业务产生影响。

Function.prototype.before = function (beforeFn) {
  var _this = this
  return function() {
    //先进行前置函数调用
    beforeFn.apply(this, arguments)
    //执行原来的函数
    return _this.apply(this, arguments)
  }
}

Function.prototype.after = function (afterFn) {
  var _this = this
  return function() {
    //先进行后置函数调用
    var result = _this.apply(this, arguments)
    afterFn.apply(this, arguments)
    //执行原来的函数
    return result
  }
}

function test() {
  console.log('1111111');
}

var test1 = test.before(function () {
  console.log('0000000');
}).after(function () {
  console.log('222222');
})

test1()

适配器模式

将一个类的接口转换成客户希望的另一个接口,适配器可以让接口不兼容类的一起工作。

class GaoDeMap {
  show() {
    console.log('高德地图开始渲染');
  }
}

class BaiduMap {
  display() {
    console.log('百度地图开始渲染');
  }
}

class GaoDeAdapter extends GaoDeMap {
  constructor() {
    super()
  }

  display() {
    this.show()
  }
}

function render(map) {
  map.display()
}

render(new GaoDeAdapter())

策略模式

策略模式定义了一系列算法,并将每个算法封装起来,使它们可以互相替换,且算法的变化不会影响使用算法的科幻,属于行为模式。

let strategry = {
  "A":(salary) => {
    return salary * 4
  },
  "B":(salary) => {
    return salary * 3
  },
  "C":(salary) => {
    return salary * 2
  },
}

function calBonus(level, salary) {
  return strategry[level](salary)
}

console.log(calBonus("A", 7000));