TS实现设计模式——单例模式

单例模式的目的是限制一个类只能被实例化一次,提供一个全局的访问点。单例模式又被分为懒汉单例模式(懒加载)和饿汉单例模式(预加载),懒汉单例模式就是在第一次调用时实例化,饿汉单例模式是类加载时就实例化。

懒汉单例模式(懒加载)
export default class RouterUtil{
  private static _routerUtil:RouterUtil

  static instance():RouterUtil{
     if(this._routerUtil===undefined){
       this._routerUtil=new RouterUtil()
     }
     return this._routerUtil
  }
}
饿汉单例模式(预加载)
export default class RouterUtil{
  private static _routerUtil:RouterUtil=new RouterUtil()

  static instance():RouterUtil
}
封装的router单例
import { RouteLocationRaw , Router } from 'vue-router'
import { Ref } from 'vue'

export default class RouterUtil {
  private static _routerUtil: RouterUtil

  static instance(): RouterUtil {
    if (this._routerUtil === undefined) {
      this._routerUtil = new RouterUtil()
    }

    return this._routerUtil
  }

  private _isSpinRef: Ref<boolean> | undefined
  private _router: Router | undefined
  private _count: number

  updateSpinRefAndRouter(isSpinRef: Ref<boolean>, router: Router): void {
    this._isSpinRef = isSpinRef
    this._router = router
  }

  private constructor() {
    this._isSpinRef = undefined
    this._router = undefined
    this._count = 0
  }

  async push(to: RouteLocationRaw): Promise<void> {
    if (this._isSpinRef !== undefined && this._router !== undefined) {
      try {
        this._isSpinRef.value = true
        await this._router.push(to)
        this._isSpinRef.value = false
        this._count += 1
      } catch (e) {
        this._isSpinRef.value = false
      }
    }
  }

  async replace(to: RouteLocationRaw): Promise<void> {
    if (this._isSpinRef !== undefined && this._router !== undefined) {
      try {
        this._isSpinRef.value = true
        await this._router.replace(to)
        this._isSpinRef.value = false
      } catch (e) {
        this._isSpinRef.value = false
      }
    }
  }

  back(): void {
    if (this._router !== undefined) {
      if (this._count !== 0) {
        this._router.back()
        this._count -= 1
      } else {
        this._router.replace({
          name: 'Home'
        }).then(() => {
          this._count = 0
        })
      }
    }
  }

  go(delta: number): void {
    if (this._router !== undefined) {
      if (this._count !== 0) {
        this._router.go(delta)
        this._count -= delta

        if (this._count < 0) {
          this._router.replace({
            name: 'Home'
          }).then(() => {
            this._count = 0
          })
        }
      }
    }
  }
}
外部访问:如下:
RouterUtil.instance().replace('/')
RouterUtil.instance().push({ name: 'giftcardList', params: { restaurantId: props.shopId } })
RouterUtil.instance().back()
RouterUtil.instance().go(-2)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值