Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
yangrenmu opened this issue Sep 22, 2020 · 0 comments
Open

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

yangrenmu opened this issue Sep 22, 2020 · 0 comments
Labels

Comments

@yangrenmu
Copy link
Owner

介绍

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

实现

假设这样一个场景,有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()
}

小结

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

@yangrenmu yangrenmu added the mode label Sep 22, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant