享元模式 📖
定义
享元模式(Flyweight Pattern),主要用于减少创建对象的数量,以减少内存占用和提高性能。
状态划分
享元模式要求将对象的属性划分为内部状态与外部 状态(状态在这里通常指属性)。享元模式的目标是尽量减少共享对象的数量,关于如何划分内部状态和外部状态,下面的几条经验提供了一些指引:
- 内部状态存储于对象内部
- 内部状态可以被一些对象共享
- 内部状态独立于具体的场景,通常不会改变
- 外部状态取决于具体的场景,并根据场景而变化,外部状态不能被共享
何时使用
- 一个程序中使用了大量的相似对象
- 由于使用了大量对象,造成很大的内在开销
- 对象的大多数状态都可以变为外部状态
- 剥离出对象的外部状态之后,可以用相对较少的共享对象取代大量对象
实现
js
class Flyweight {
constructor(make, model, processor) {
this.make = make
this.model = model
this.processor = processor
}
}
const FlyWeightFactory = (function () {
const flyweights = {}
return {
get: function (make, model, processor) {
if (!flyweights[make + model]) {
flyweights[make + model] = new Flyweight(make, model, processor)
}
return flyweights[make + model]
},
getCount: function () {
let count = 0
for (let f in flyweights) count++
return count
},
}
})()
class ComputerCollection {
computers = {}
count = 0
add(make, model, processor, memory, tag) {
this.computers[tag] = new Computer(
make,
model,
processor,
memory,
tag,
)
this.count++
}
get(tag) {
return this.computers[tag]
}
getCount() {
return this.count
}
}
class Computer {
constructor(make, model, processor, memory, tag) {
this.flyweight = FlyWeightFactory.get(make, model, processor)
this.memory = memory
this.tag = tag
}
getMake = function () {
return this.flyweight.make
}
}
const computers = new ComputerCollection()
computers.add('Dell', 'Studio XPS', 'Intel', '5G', 'Y755P')
computers.add('Dell', 'Studio XPS', 'Intel', '6G', 'X997T')
computers.add('Dell', 'Studio XPS', 'Intel', '2G', 'U8U80')
computers.add('Dell', 'Studio XPS', 'Intel', '2G', 'NT777')
computers.add('Dell', 'XPS', 'Intel', '2G', '0J88A')
computers.add('HP', 'Envy', 'Intel', '4G', 'CNU883701')
computers.add('HP', 'Envy', 'Intel', '2G', 'TXU003283')
console.log('Computers: ' + computers.getCount())
console.log('Flyweights: ' + FlyWeightFactory.getCount())