1. class LoginForm {
  2. private state: string = 'hide' // or show
  3. private constructor() {}
  4. show() {
  5. if (this.state === 'show') {
  6. console.log('already show');
  7. return;
  8. }
  9. console.log('显示的逻辑')
  10. this.state = 'show'
  11. }
  12. hide() {
  13. if (this.state === 'hide') {
  14. console.log('already hide');
  15. return;
  16. }
  17. console.log('隐藏的逻辑')
  18. this.state = 'hide'
  19. }
  20. private static instance: LoginForm | null = null
  21. static getInstance(): LoginForm {
  22. // 在 static this => LoginForm
  23. if (this.instance == null) {
  24. this.instance = new LoginForm()
  25. }
  26. return this.instance;
  27. }
  28. }
  29. const login1 = LoginForm.getInstance();
  30. const login2 = LoginForm.getInstance();
  31. console.log(login1 === login2) // true

其他

  • 自定义事件 EventBus 全局唯一
  • Vuex Redux 的 store 全局唯一
  • (严格的单例模式应用不多,但单例的思想随处可见)