1. function genGetInstance() {
  2. let instance = null
  3. class Singleton {}
  4. return () => {
  5. if (instance === null) {
  6. instance = new Singleton();
  7. }
  8. return instance
  9. }
  10. }
  11. const getInstance = genGetInstance();
  12. const s1 = getInstance();
  13. const s2 = getInstance();
  14. console.log(s1, s2, s1 === s2) // Singleton类,Singleton类,true
  1. let instance
  2. class Singleton {}
  3. export default () => {
  4. if (instance === null) {
  5. instance = new Singleton();
  6. }
  7. return instance
  8. }

是否符合设计原则

  • 内部封装 getInstance,高内聚,低耦合

注意:Java等多线程语言,单例要加线程锁