Repository navigation
Expand file tree
/
Copy path03-结构型模式-享元模式.js
More file actions
89 lines (74 loc) · 2.81 KB
/
Copy path03-结构型模式-享元模式.js
File metadata and controls
89 lines (74 loc) · 2.81 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
let examCarNum = 0 // 驾考车总数
/* 驾考车对象 */
class ExamCar {
constructor(carType) {
examCarNum++
this.carId = examCarNum
this.carType = carType ? '手动档' : '自动档'
this.usingState = false // 是否正在使用
}
/* 在本车上考试 */
examine(candidateId) {
return new Promise((resolve => {
this.usingState = true
console.log(`考生- ${ candidateId } 开始在${ this.carType }驾考车- ${ this.carId } 上考试`)
setTimeout(() => {
this.usingState = false
console.log(`考生- ${ candidateId } 在${ this.carType }驾考车- ${ this.carId } 上考试完毕`)
resolve() // 0~2秒后考试完毕
}, Math.random() * 2000)
}))
}
}
/* 手动档汽车对象池 */
ManualExamCarPool = {
_pool: [], // 驾考车对象池
_candidateQueue: [], // 考生队列
/* 注册考生 ID 列表 */
registCandidates(candidateList) {
candidateList.forEach(candidateId => this.registCandidate(candidateId))
},
/* 注册手动档考生 */
registCandidate(candidateId) {
const examCar = this.getManualExamCar() // 找一个未被占用的手动档驾考车
if (examCar) {
examCar.examine(candidateId) // 开始考试,考完了让队列中的下一个考生开始考试
.then(() => {
const nextCandidateId = this._candidateQueue.length && this._candidateQueue.shift()
nextCandidateId && this.registCandidate(nextCandidateId)
})
} else this._candidateQueue.push(candidateId)
},
/* 注册手动档车 */
initManualExamCar(manualExamCarNum) {
for (let i = 1; i <= manualExamCarNum; i++) {
this._pool.push(new ExamCar(true))
}
},
/* 获取状态为未被占用的手动档车 */
getManualExamCar() {
return this._pool.find(car => !car.usingState)
}
}
ManualExamCarPool.initManualExamCar(3) // 一共有3个驾考车
ManualExamCarPool.registCandidates([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) // 10个考生来考试
/**
* node事件循环
*/
// const crypto = require('crypto')
// const start = Date.now()
// crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', () => {
// console.log('1:', Date.now() - start)
// })
// crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', () => {
// console.log('2:', Date.now() - start)
// })
// crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', () => {
// console.log('3:', Date.now() - start)
// })
// crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', () => {
// console.log('4:', Date.now() - start)
// })
// crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', () => {
// console.log('5:', Date.now() - start)
// })