zoukankan      html  css  js  c++  java
  • JavaScript设计模式样例十二 —— 享元模式

    享元模式(Flyweight Pattern)

    定义:减少创建对象的数量,以减少内存占用和提高性能。
    目的:用共享技术有效地支持大量细粒度的对象。
    场景:系统中有大量对象。
    // 构建享元对象
    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)
    }

    Git地址:https://github.com/skillnull/Design-Mode-Example

  • 相关阅读:
    获取定位
    关于meta 总结
    关于微信 ios的部分兼容(摇动播放)
    mysql
    js_DOM的导航属性--Dom_event事件
    IO阻塞与IO非阻塞2
    进程池
    生产消费者模型
    队列----------------多线程利器
    信号量
  • 原文地址:https://www.cnblogs.com/Man-Dream-Necessary/p/12450564.html
Copyright © 2011-2022 走看看