使用代理实现单例

作者:xie392地址:https://v.douyin.com/ie9K97AL/更新时间:2024-12-21

案例代码

1
class MyVideo {
2
constructor(a, b) {
3
this.a = a;
4
this.b = b;
5
}
6
7
sayHello() {
8
console.log("hello");
9
}
10
}
11
12
function isSame(value1, value2) {
13
if (value1.length !== value2.length) {
14
return false;
15
}
16
17
for (let i = 0; i < value1.length; i++) {
18
if (value1[i] !== value2[i]) {
19
return false;
20
}
21
}
22
23
return true;
24
}
25
26
function singaleton(className) {
27
let ins, parameters;
28
return new Proxy(className, {
29
construct(target, args) {
30
if (!ins) {
31
ins = new target(target, ...args);
32
parameters = args;
33
}
34
if (!isSame(parameters, args)) {
35
throw new Error("参数不一致");
36
}
37
return ins;
38
},
39
});
40
}
41
42
const Video = singaleton(MyVideo);
43
44
const v1 = new Video();
45
const v2 = new Video();
46
47
console.log("v1 === v2:", v1 === v2);

输出结果:

1
v1 === v2: true