享元模式(Flyweight Pattern)
|
1 2 3 |
定义:减少创建对象的数量,以减少内存占用和提高性能。 目的:用共享技术有效地支持大量细粒度的对象。 场景:系统中有大量对象。 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
// 享元对象:只保存可共享的内部状态 class Model { constructor(gender) { this.gender = gender Object.freeze(this) } takePhoto({ name, clothes }) { console.log( `${this.gender}模${name}穿${clothes}拍了照` ) } } // 享元工厂 class ModelFactory { static #models = new Map() static getModel(gender) { if (!this.#models.has(gender)) { this.#models.set(gender, new Model(gender)) } return this.#models.get(gender) } static getCount() { return this.#models.size } } // 外部状态管理器 class ClothingShootManager { static #records = new Map() static addClothes(id, gender, clothes) { this.#records.set(id, { id, name: `${gender}${id}`, clothes, model: ModelFactory.getModel(gender) }) } static takePhoto(id) { const record = this.#records.get(id) if (!record) { throw new Error(`不存在编号为 ${id} 的拍摄记录`) } record.model.takePhoto({ name: record.name, clothes: record.clothes }) } } for (let i = 0; i < 10; i++) { ClothingShootManager.addClothes(i, '男', `服装${i}`) ClothingShootManager.takePhoto(i) } for (let i = 10; i < 20; i++) { ClothingShootManager.addClothes(i, '女', `服装${i}`) ClothingShootManager.takePhoto(i) } console.log(ModelFactory.getCount()) // 2 |

