-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy path0-factory.js
More file actions
42 lines (33 loc) · 827 Bytes
/
0-factory.js
File metadata and controls
42 lines (33 loc) · 827 Bytes
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
'use strict';
const poolify = (factory) => {
const instances = new Array(5).fill(null).map(() => factory.create());
const acquire = () => {
const instance = instances.pop();
console.log('Get from pool, count =', instances.length);
return instance;
};
const release = (instance) => {
instances.push(instance);
console.log('Recycle item, count =', instances.length);
};
return { acquire, release };
};
class Connection {
constructor(index) {
this.url = `http://10.0.0.1/${index}`;
}
}
class ConnectionFactory {
constructor() {
this.index = 0;
}
create() {
return new Connection(this.index++);
}
}
// Usage
const factory = new ConnectionFactory();
const pool = poolify(factory);
const connection = pool.acquire();
console.log(connection);
pool.release(connection);