享元模式(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 | // 构建享元对象 class Modal {     constructor (id, gender) {         this.gender = gender         this.name = `${gender}${id}`     } } // 构建享元工厂 class ModalFactory {     // 单例模式     static create (id, gender) {         if (this[gender]) {             return this[gender]         }         return this[gender] = new Modal(id, gender)     } } // 管理外部状态 class TakeClothersManager {     // 添加衣服款式     static addClothes (id, gender, clothes) {         const modal = ModalFactory.create(id, gender)         this[id] = {             clothes,             modal         }     }     // 拍照     static takePhoto (id) {         const obj = this[id]         console.log(`${obj.modal.gender}模${obj.modal.name}穿${obj.clothes}拍了照`)     } } for (let i = 0; i < 10; i++) {     TakeClothersManager.addClothes(i, '男', `服装${i}`)     TakeClothersManager.takePhoto(i) } for (let i = 10; i < 20; i++) {     TakeClothersManager.addClothes(i, '女', `服装${i}`)     TakeClothersManager.takePhoto(i) } | 
Github地址:https://github.com/skillnull/Design-Mode-Example[……]