从 Javascript 看享元模式

63 阅读1分钟

使用场景

当我们创建的对象可以进行复用,不需要重新创建的时候,我们就可以使用旧的对象,这种就是享元模式。

享元模式

享元模式的意义在于减少对象的创建,有利于提高性能。如果对象是有状态的,那么在共享的时候还需要进行状态的重置。一般共享的都是无状态的对象。例如单纯的提供一些方法调用和固定的属性。通常配合一个总的控制对象进行管理,提供固定数量的共享对象。

使用方法

比如说线程池

    class Thread {
        constructor() {
            this.unused = true
        }
        serve() {
            this.unused = false
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    this.unused = true
                    resolve()
                }, 2000)
            })
        }
    }

    class Pool {
        constructor() {
            this.queue = []
            this.pool = [new Thread(), new Thread(), new Thread()]
        }
        
        useThread(user) {
            const thread = this.pool.find(thread => thread.unused)
            if (thread) {
                thread.serve(user).then(this.pick)
            } else {
                this.wait(user)
            }
        }
        
        wait(user) {
            this.queue.push(user)
        }
        
        pick() {
            if (this.queue.length > 0) {
                const user = this.queue.shift()
                this.useThread(user)
            }
        }
    }