手写一个 LazyMan,实现 sleep 机制
手写一个 LazyMan,实现 sleep 机制
手写 LazyMan
- 支持 sleep 和 eat 两个方法
- 支持链式调用
LazyMan 示例
const me = new LazyMan('友谊')
me.eat('苹果').eat('香蕉').sleep(5).eat('葡萄')
// 打印结果如下:
// '友谊 eat 苹果'
// '友谊 eat 香蕉'
// 等待5s
// '友谊 eat 葡萄'
代码设计
- 由于有 sleep 功能,函数不能直接在调用时触发
- 初始化一个列表,把函数注册进去
- 由每个 item 触发next 执行(遇到 sleep 则异步触发)
class LazyMan {
private name: string
private tasks: Function[] = []; // 任务列表
constructor(name: string) {
this.name = name;
setTimeout(() => {
this.next();
})
}
// next
private next() {
const task = this.tasks.shift(); // 取出当前 tasks 的第一个任务
if(task) task()
}
eat(food: string) {
const task = () => {
console.info(`${this.name} eat ${food}`)
// 执行下一个
this.next(); // 立刻执行下一个任务
}
this.tasks.push(task);
return this // 链式调用
}
sleep(seconds: number) {
const task = () => {
console.info(`${this.name} 开始睡觉`)
setTimeout(()=> {
console.info(`${this.name} 已经睡完了${seconds}s,开始执行下一个任务`)
this.next(); xx秒之后再执行下一个任务;
}, seconds * 1000)
}
this.tasks.push(task);
return this; // 链式调用
}
}
const me = new LazyMan('友谊')
me.eat('苹果').eat('香蕉').sleep(5).eat('葡萄')
LazyMan,实现sleep机制重点总结:
- 任务队列
- 触发 next
- sleep 异步触发

