SOURCE

// 懒汉 类
class LazyManClass {
    constructor(name) {
        this.name = name
        this.queue = [] // 队列
        console.log(`Hi! This is ${name}`)

        // 延迟调度
        setTimeout(() => {
            this.next()
        }, 0)
    }

    // 调度方法
    next() {
        const fnc = this.queue.shift()
        fnc && fnc()
    }

    /**
     * 注册函数方法
     * @param {*} fn 要注册的函数 
     * @param {*} isFirst 是否注册在队列最前
     */
    register(fn, isFirst) {
        if (isFirst) {
            this.queue.unshift(fn)
        } else {
            this.queue.push(fn)
        }
    }

    // 吃
    eat(food) {
        const _eat = () => {
            console.log(`Eat ${food}~`)
            this.next()
        }
        this.register(_eat)
        return this
    }

    // 睡在最前面
    sleepFirst(s) {
        return this.sleep(s, true)
    }

    // 睡觉
    sleep(s, isFirst = false) {
        const timeout = s * 1000
        const _sleep = () => {
            console.log(`Wake up after ${s}`)
            setTimeout(() => {
                this.next()
            }, timeout)
        }
        this.register(_sleep, isFirst)
        return this
    }
}

// 懒汉 返回一个懒汉实例
function LazyMan(name) {
    return new LazyManClass(name)
}
LazyMan('小明').eat('午餐').eat('晚餐').sleepFirst(2).eat('早餐');
console 命令行工具 X clear

                    
>
console