JavaScript设计模式(九):享元模式

158 阅读1分钟

介绍

享元模式,是一种用于优化性能的模式,意在减少创建对象。

实现

假设这样一个场景,有100块金砖需要搬到家里。
方案一:找一百个人,一人搬一块。程序里也许会这样写。

const People = function (count) {
  this.count = count
}
People.prototype.move = function () {
  console.log(`第 ${this.count} 块金砖已搬回家~`)
}
for (let i = 1; i <= 100; i++) {
  const people = new People(i)
  people.move()
}

方案二:找一个人,将这一百块金砖搬回家。

const People = function () {
  this.count = 0
}
People.prototype.move = function () {
  console.log(`第 ${this.count} 块金砖已搬回家~`)
}
const people = new People()
for (let i = 1; i <= 100; i++) {
  people.count = i
  people.move()
}

小结

当程序中,存在很多相似对象时,享元模式可以很好的解决大量对象带来的性能问题。