Last active
April 9, 2024 06:28
-
-
Save hevi1991/3dcee40f32c1b44f254f3a11712ab78f to your computer and use it in GitHub Desktop.
JavaScript 使用代理来实现单例模式
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export function singleton(clazz) { | |
| let instance; | |
| return new Proxy(clazz, { | |
| construct(target, args) { | |
| if (instance) { | |
| return instance; | |
| } else { | |
| instance = new target(...args); | |
| return instance; | |
| } | |
| }, | |
| }); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { singleton } from "./singleton.js"; | |
| class Video { | |
| constructor(name) { | |
| this.name = name; | |
| } | |
| play() { | |
| console.log(`${this.name} is playing`); | |
| } | |
| } | |
| export default singleton(Video); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Video from "./singletonClass.js"; | |
| const v2 = new Video(`v2`); | |
| const v = new Video(`v`); | |
| v.play(); | |
| v2.play(); | |
| console.log(v === v2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
js singleton by using Proxy