function genGetInstance() {let instance = nullclass Singleton {}return () => {if (instance === null) {instance = new Singleton();}return instance}}const getInstance = genGetInstance();const s1 = getInstance();const s2 = getInstance();console.log(s1, s2, s1 === s2) // Singleton类,Singleton类,true
let instanceclass Singleton {}export default () => {if (instance === null) {instance = new Singleton();}return instance}
是否符合设计原则
- 内部封装 getInstance,高内聚,低耦合
注意:Java等多线程语言,单例要加线程锁
